我理解在使用外连接时JOIN子句和WHERE子句中的过滤器是不同的。让我们说我有这两张桌子。
table1
id | value
---+------
1 | 11
2 | 12
table2
id | value
---+------
1 | 101
现在,如果我查询
select a.id as id1, a.value as value1, b.value as value2
from table1 as a
left join table2 on a.id=b.id and a.value=11
结果就是这样,一个额外的行,其值为1 = 12
id1 | value1 | value2
----+--------+--------
1 | 11 | 101
2 | 12 | NULL
但是,如果我将过滤器放在where子句中,它会给我我想要的东西。问题是它为什么会这样?
答案 0 :(得分:0)
左连接示例中使用的第二个条件限制将考虑连接哪些行。
select f1.id as id1, t1.value as value1, t2.value as value2 from t1 left join t2 on t1.id=t2.id AND T2.VALUE=11 t1 id | value ---+------ 1 | 11 ONLY join on this row because t1.value=11 2 | 12 t2 id | value ---+------ 1 | 101 this has t1.id=t2.id, so it does get joined which would produce this final result: id1 | value1 | value 2 ----+--------+-------- 1 | 11 | 101 2 | 12 | NULL
将谓词T2.VALUE=11
移动到where子句有一系列不同的事件,如下所示:
select f1.id as id1, t1.value as value1, t2.value as value2 from t1 left join t2 on t1.id=t2.id WHERE T2.VALUE=11 t1 id | value ---+------ 1 | 11 this row does meet t1.id=t2.id, so it gets joined 2 | 12 this row does NOT meet t1.id=t2.id, FAILS to join t2 id | value ---+------ 1 | 101 this row does meet t1.id=t2.id, so it gets joined which would produce this INTERIM result: id1 | value1 | value 2 ----+--------+-------- 1 | 11 | 101 2 | 12 | NULL NOW the where clause is considered id1 | value1 | value 2 ----+--------+-------- 1 | 11 | 101 T2.VALUE does equal 11 so this row will be returned 2 | 12 | NULL T2.VALUE does NOT = 11 so this row is NOT returned Thus the final result is: id1 | value1 | value 2 ----+--------+-------- 1 | 11 | 101