摘要:SQL Server - Cross Join + Left Join
這次的問題,會是我有三個麵包,
兩個訂單,兩個訂單分別有訂不同的麵包。
但我要join出來的資料,會是兩個訂單搭配三個麵包,但沒有訂到的麵包,(不存在的麵包訂單資料,要使用NULL)
解決方法,先用卡式積。
select * from brand as A cross join
(select distinct order_id from order_brand) as B;
再left join 訂單資料,
就會把沒有的麵包資訊,顯示NULL
select D.id,D.order_id,C.brand_id,C.amount from
(select * from brand as A cross join
(select distinct order_id from order_brand) as B) as D
left join order_brand as C on D.id = C.brand_id and D.order_id = C.order_id;