SQL JOIN ON

Join on 內的篩選條件會影響Join內容,但不會影響Join總筆數。

Join 後的 where 條件則會影響Join總筆數,但Join內容不受影響。

例如:
table_a
id num
1 3
2 5
3 1

table_b
id num
1 9
2 8
4 10

select a.* , b.num
from table_a a left join table_b b
on a.id = b.id

id num num
1 3 9
2 5 8
3 1 null

select a.* , b.num
from table_a a left join table_b b
on a.id = b.id and a.num > 4

id num num
1 3 null
2 5 8
3 1 null
:原本可以對應出table_b id=1 ,num = 9的資料,但是因為在on子句內多加了 a.num > 4,導致table_a id = 1 , num = 3的資料不會去對應table_b id=1 , num = 9的資料。

select a.* , b.num
from table_a a left join table_b b
on a.id = b.id
where a.num > 4

id num num
1 3 9
2 5 8
3 1 null

id num num
2 5 8

This entry was posted in 資料庫 and tagged . Bookmark the permalink.

發表迴響

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

連結到 %s