根据我的理解,FULL OUTER JOIN
是LEFT OUTER JOIN
和RIGHT OUTER JOIN
的组合。在这种情况下,它只是连接两个表与所有条目。请告诉我为什么我们为ON
提供“FULL OUTER JOIN
”条款?或者解释如何应用ON子句或者它在查询中有什么区别?
例如查询:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
答案 0 :(得分:5)
此图表将帮助您了解连接。
答案 1 :(得分:1)
ON 是加入条件,将用于除交叉加入之外的所有联接类型
全外连接类似于:
SELECT employee.LastName, employee.DepartmentID,
department.DepartmentName, department.DepartmentID
FROM employee
INNER JOIN department ON employee.DepartmentID = department.DepartmentID
UNION ALL
SELECT employee.LastName, employee.DepartmentID,
CAST(NULL AS VARCHAR(20)), CAST(NULL AS INTEGER)
FROM employee
WHERE NOT EXISTS (
SELECT * FROM department
WHERE employee.DepartmentID = department.DepartmentID)
UNION ALL
SELECT CAST(NULL AS VARCHAR(20)), CAST(NULL AS INTEGER),
department.DepartmentName, department.DepartmentID
FROM department
WHERE NOT EXISTS (
SELECT * FROM employee
WHERE employee.DepartmentID = department.DepartmentID)
测试数据:
CREATE TABLE department
(
DepartmentID INT,
DepartmentName VARCHAR(20)
);
CREATE TABLE employee
(
LastName VARCHAR(20),
DepartmentID INT
);
INSERT INTO department VALUES(31, 'Sales');
INSERT INTO department VALUES(33, 'Engineering');
INSERT INTO department VALUES(34, 'Clerical');
INSERT INTO department VALUES(35, 'Marketing');
INSERT INTO employee VALUES('Rafferty', 31);
INSERT INTO employee VALUES('Jones', 33);
INSERT INTO employee VALUES('Heisenberg', 33);
INSERT INTO employee VALUES('Robinson', 34);
INSERT INTO employee VALUES('Smith', 34);
INSERT INTO employee VALUES('John', NULL);
答案 2 :(得分:1)
cross join
在两个表之间生成笛卡尔积,返回所有行的所有可能组合。它有 no on clause ,因为您只是将所有内容加入到所有内容中。
full outer join
是左外连接和右外连接的组合。它返回两个表中与查询的where子句匹配的所有行,如果这些行不能满足on条件,则为未填充的字段设置空值。