📜  SQL FULL JOIN(1)

📅  最后修改于: 2023-12-03 15:20:14.393000             🧑  作者: Mango

SQL FULL JOIN

SQL FULL JOIN is used to retrieve data from multiple tables where both tables can contain matching data. It is similar to the LEFT JOIN and the RIGHT JOIN, but it returns all the rows from both tables.

Syntax:

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name;

OR

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name
UNION
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

Note: The first syntax is specific to SQL Server while the second syntax is more generic.

Let us understand the FULL JOIN with the help of an example:

Example

Consider two tables, 'Customers' and 'Orders', as shown below:

Customers Table

| CustomerID | CustomerName | ContactName | Country | |------------|--------------|-------------|---------| | 1 | Alfreds | Maria | Germany | | 2 | Ana Trujillo | Ana | Mexico | | 3 | Antonio | Antonio | Mexico | | 4 | Around the | Thomas | UK | | 5 | Berglunds | Christina | Sweden |

Orders Table

| OrderID | CustomerID | OrderDate | |---------|-----------|------------| | 1 | 3 | 2020-01-01 | | 2 | 1 | 2020-01-02 | | 3 | 2 | 2020-01-03 | | 4 | 5 | 2020-01-04 | | 5 | 4 | 2020-01-05 |

We want to retrieve all the records from both tables where the 'CustomerID' matches in both tables.

SQL Query:

SELECT Customers.CustomerID, Customers.CustomerName, Orders.OrderID, Orders.OrderDate
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID;

Output:

| CustomerID | CustomerName | OrderID | OrderDate | |------------|--------------|---------|-----------| | 1 | Alfreds | 2 | 2020-01-02 | | 2 | Ana Trujillo | 3 | 2020-01-03 | | 3 | Antonio | 1 | 2020-01-01 | | 4 | Around the | 5 | 2020-01-05 | | 5 | Berglunds | 4 | 2020-01-04 | | NULL | NULL | 6 | 2020-01-06 |

As you can see, all the records from both tables where the 'CustomerID' matches have been retrieved, with the missing values filled with NULL.

That's all you need to know about SQL FULL JOIN. Use it whenever you require data from multiple tables where both tables can have matching data.