SQL - Left Outer Join

Left outer join

  • 可以 query data 2 個以上的 tables
SELECT select_list
FROM t1
LEFT JOIN t2
ON join_condition;
  • t1 是左邊的 table
  • t2 是右邊的 table
  • left join 會從 left table (t1) 開始執行, 在 join_condition 的條件之下, 在 left table 的每一個 row 都會出現一遍, 但是如果跟 right table (t2) 有相同的 match, 就會只出現一次, 如果right table 並沒有相對應的 match, 那麼 left join 的資料還是會出現, 不過 right table 的 fields 就會是 null
  • return rows 會和 left table (t1) 的 row 數一樣
select *
from person p
left join address a
using(address_id);
  • outer join 要找出 null 值也會很方便, 因為只要在後面加上 where clause
select *
from person p
left join address a
using(address_id)
where p.address_id is null;
  • on vs where
    如果在 join 中, 要一次符合相同的條件, 就要使用 on + and, 但是如果是先縮小範圍後去篩選我所要的條件, 就會使用 where
select *
from person p
left join address a
on p.address_id = a.address_id
and p.address_id = 1;
select *
from person p
left join address a
on p.address_id = a.address_id
where p.address_id = 1;

留言