如果表的左侧 (table1) 或右侧 (table2) 记录中有匹配项,则关键字 FULL OUTER JOIN 返回所有记录。
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition
在本教程中,我们将使用著名的示例数据库“Northwind”。
以下是表“Customers”(“客户”)中的示例:
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 5021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 5023 | Mexico |
4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
以及表“Orders”(“订单”)中的示例:
ProductID | OrderID | CustomerID | EmployeeID | OrderDate | ShipperID |
---|---|---|---|---|---|
1 | 10248 | 90 | 5 | 1996-07-04 | 3 |
2 | 10249 | 81 | 6 | 1996-07-05 | 1 |
3 | 10250 | 34 | 4 | 1996-07-08 | 2 |
4 | 10251 | 84 | 3 | 1996-07-08 | 1 |
5 | 10252 | 76 | 4 | 1996-07-09 | 2 |
以下 SQL 语句选择所有客户和所有订单:
Run SQLSELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName
结果集中的示例可能如下所示:
CustomerName | OrderID |
---|---|
Null | 10309 |
Null | 10310 |
Alfreds Futterkiste | Null |
Ana Trujillo Emparedados y helados | 10308 |
Antonio Moreno Taquería | Null |