2017-10-21 19 views
0

我瞭解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

上子句中的謂詞確定從左側的行是否與一個連接在右邊。 where子句中的謂詞在所有連接行匹配並且外部行保留在連接結果之後運行。 –

回答

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