📅  最后修改于: 2023-12-03 15:02:08.598000             🧑  作者: Mango
When working with SQL, you may come across the terms "join" and "union". While both of these commands can be used to combine data from multiple tables, they have different uses and syntax.
A join is used to combine rows from two or more tables based on a related column between them. There are several types of joins, including inner join, left join, right join, and full outer join.
An inner join returns only the rows that have matching values in both tables being joined. The syntax for an inner join is as follows:
SELECT *
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
A left join returns all the rows from the left table (table1) and the matching rows from the right table (table2). If there is no matching row in the right table, NULL values are returned. The syntax for a left join is as follows:
SELECT *
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
A right join returns all the rows from the right table (table2) and the matching rows from the left table (table1). If there is no matching row in the left table, NULL values are returned. The syntax for a right join is as follows:
SELECT *
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;
A full outer join returns all the rows from both tables, including NULL values where there is no match. The syntax for a full outer join is as follows:
SELECT *
FROM table1
FULL OUTER JOIN table2
ON table1.column = table2.column;
A union is used to combine the result sets of two or more SELECT statements into a single result set. The SELECT statements must have the same number of columns and data types. Duplicate rows are automatically removed unless the UNION ALL option is used.
The syntax for a union is as follows:
SELECT column1, column2
FROM table1
UNION
SELECT column1, column2
FROM table2;
In summary, a join is used to combine rows from different tables based on a related column, while a union is used to combine the result sets of two or more SELECT statements. Understanding these concepts and knowing when to use each one is important for any SQL developer.