6

我需要基于一个共同的主键加入 4 个表。如果 sqlite 实现了完整的外部连接,它可能看起来像这样(不考虑优化)。

SELECT S.pair, C.ball, P.bluejeans, B.checkered 
FROM Socks S 
FULL OUTER JOIN Caps C 
FULL OUTER JOIN Pants P 
FULL OUTER JOIN Boxers B 
WHERE S.color = C.color AND S.color = P.color AND S.color = B.color;

我看起来很长很努力,我发现最好的是这个 2 table sqlite full join 用左连接和联合 alls 实现:

SELECT employee.*, department.* 
FROM employee LEFT JOIN department 
ON employee.DepartmentID = department.DepartmentID 
UNION ALL SELECT employee.*, department.* 
FROM   department LEFT JOIN employee 
ON employee.DepartmentID = department.DepartmentID 
WHERE  employee.DepartmentID IS NULL;

我正在尝试修改它以适用于超过 2 个表,但我是 SQL 新手,我并没有走得太远。是否有可能在合理的时间内得到这个结果?

我认为我对 3 个表有正确的实现(可能不正确),但我似乎仍然无法为 4 个表实现它。这是我对 3 个表的实现:

SELECT S.pair, C.ball, P.bluejeans 
FROM Socks S LEFT JOIN Caps C LEFT JOIN Pants P 
ON C.color = S.color AND P.color = S.color 
UNION ALL 
SELECT S.pair, C.ball, P.bluejeans 
FROM Socks S LEFT JOIN Caps C LEFT JOIN Pants P 
ON S.color = C.color AND S.color = P.color 
WHERE S.color IS NULL;

任何帮助深表感谢

4

1 回答 1

7

两个表之间A以及B在 SQLite 中的完全外连接的一般构造确实是:

SELECT ... FROM A LEFT JOIN B ON ...
UNION ALL
SELECT ... FROM B LEFT JOIN A ON ... WHERE A.key IS NULL

现在为and之间的完全外连接创建一个视图SocksCapsSocksCaps

CREATE VIEW SocksCaps AS
SELECT ... FROM Socks LEFT JOIN Caps ON ...
UNION ALL
SELECT ... FROM Caps LEFT JOIN Socks ON ... WHERE Socks.color IS NULL

Pants对和做同样的事情Boxers

然后像对待表一样对待这些视图,并使用相同的结构进行完全外连接:

SELECT ... FROM SocksCaps LEFT JOIN PantsBoxers ON ...
UNION ALL
SELECT ... FROM PantsBoxers LEFT JOIN SocksCaps ON ... WHERE SocksCaps.color IS NULL
于 2012-10-06T13:08:38.517 回答