为什么此查询在某些情况下会产生重复项?
Table_1
ID
1
2
3
Table_2
ID
1
2
4
Table_3
ID
1
3
4
询问:
SELECT COALESCE(Table_1.ID, Table_2.ID, Table_3.ID)
FROM Table_1
FULL OUTER JOIN TABLE_2
ON Table1.ID=Table_2.ID
FULL OUTER JOIN TABLE_3
ON Table1.ID=Table3.ID;
结果:
1
2
3
4
4
该查询复制 T1 为空且 T2/T3 共享相同值的所有值。删除任何其他组合的重复项。
最佳答案
这有点难以解释。如果您显示其他 ID,您将看到所发生的全部情况:
"coalesce" "id1" "id2" "id3"
1 1 1 1
2 2 2 .
3 3 . 3
4 . 4 .
4 . . 4
可以看到结果here .
所以,你得到一行是因为 t1 & t2 用
t2.id = 4
创建了一行和 t1.id = null
当它们不匹配时。然后,当 t3.id = 4
时,您会得到同样的结果。 .比较的是t1.id
- 所以你得到另一排。与 t2.id
没有可比性.我怀疑你更倾向于这样的逻辑:
select coalesce(t1.id, t2.id, t3.id)
from t1 full join
t2
using (id) full join
t3
using (id);
Here是 SQL fiddle 。
关于SQL 全外连接 WITH/Coalesce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45291131/