SQL完全加入优先级

时间:2014-07-18 15:09:25

标签: sql join

假设您有3个表(tableA,tableB,tableC),每个表都有一个ID列和一个Value列。有些表的ID匹配,但有些则不匹配。 如果你这样做:

SELECT tableA.ID FROM tableA
FULL JOIN tableB ON (tableA.ID = tableB.ID)
FULL JOIN tableC ON (tableA.ID = tableC.ID)

这与以下不同:

SELECT tableA.ID FROM tableA
FULL JOIN tableB ON (tableA.ID = tableB.ID)
FULL JOIN tableC ON (tableB.ID = tableC.ID)

或者:

SELECT Y.ID FROM
(SELECT tableA.ID FROM tableA
FULL JOIN tableB ON (tableA.ID = tableB.ID)) X
FULL JOIN tableC ON (X.ID = tableC.ID)) Y

???有人请解释是否存在差异。感谢。

[Oracle SQL Developer版本4.02.15.21]

1 个答案:

答案 0 :(得分:1)

首先,这里有3个语句,语法清理:

SELECT COALESCE(a.ID,b.ID,c.ID)
FROM      tableA a
FULL JOIN tableB b ON a.ID = b.ID
FULL JOIN tableC c ON a.ID = c.ID

SELECT COALESCE(a.ID,b.ID,c.ID)
FROM      tableA a
FULL JOIN tableB b ON a.ID = b.ID
FULL JOIN tableC c ON b.ID = c.ID

SELECT COALESCE(X.ID,c.ID) 
FROM
( SELECT    COALESCE(a.ID ,b.ID) ID
  FROM      tableA a
  FULL JOIN tableB b ON a.ID = b.ID) X
FULL JOIN   tableC c ON X.ID = c.ID

令人惊讶的是,第一个语句的语法产生了重复的值,但语句2和3的工作方式与宣传的一样。

编辑:进一步测试时,语句1和2很容易重复,具体取决于哪些表重叠。声明3似乎是唯一可靠的方法。

SQLFiddle