我有一个SQL查询
SELECT * FROM A FULL OUTER JOIN B ON A.z = B.z WHERE A.z = 1 OR B.z = 1
其中A.z和B.z是主键。
目的是在两个表上进行完全外连接,同时它们的主键与给定值匹配 - 这样只返回一行。
但是我对如何将它扩展到3个或更多表感到困惑。它们的主键与给定索引匹配的限制因此总共只返回一行仍然存在。你是怎么做到的?
答案 0 :(得分:10)
首先请注意,在提供的查询中,您请求的FULL OUTER JOIN
可以重写为:
SELECT *
FROM (SELECT * FROM A WHERE z = 1) A
FULL OUTER JOIN (SELECT * FROM B WHERE z = 1) B ON A.z = B.z
使(IMO)更清楚数据源是什么以及连接条件是什么。有一会儿,在WHERE
条件下,我觉得你真的想要一个INNER JOIN。
有了这个,你可以更容易地扩展:
SELECT *
FROM (SELECT * FROM A WHERE z = 1) A
FULL OUTER JOIN (SELECT * FROM B WHERE z = 1) B ON A.z = B.z
FULL OUTER JOIN (SELECT * FROM C WHERE z = 1) C ON COALESCE(A.z,B.z) = C.z
FULL OUTER JOIN (SELECT * FROM D WHERE z = 1) D ON COALESCE(A.z,B.z,C.z) = D.z