天天看點

多表聯查left join

表一 T1結構 PID,PNAME

多表聯查left join

表二 T2結構 IPID,PID,PNAME,AGE

多表聯查left join

第一種用 , 進行分割多表聯查

select a.pid,b.ipid from t1 a , t2 b

where a.pid = b.pid and a.pid = ‘0828’ and b.ipid = ‘123’

查詢結果

多表聯查left join

第二種用left join 在on 中添加多個條件進行聯查

select a.pid,b.ipid from t1 a left join t2 b on a.pid = b.pid and b.ipid = ‘123’

where a.pid = ‘0828’

查詢結果

多表聯查left join

第三種用left join 在on 之後在where中添加

select a.pid,b.ipid from t1 a left join t2 b on a.pid = b.pid

where a.pid = ‘0828’ and b.ipid = ‘123’

查詢結果

多表聯查left join

*

其中第一種與第三種,如果ipid查詢不到結果,那麼會因為where 條件是對查詢後結果進行整體篩選,這樣,如果ipid不存在,那麼結果集就會傳回 空

*

但是第二種方法中,把b.ipid放到了 on 之後,這樣在 left join 拼接臨時表時,即便 b表中沒有資料,也會因為left join 查詢出左表的資料 ,将兩個表合并成 左表資料 + 空的右表 這樣做統一篩選時,如果符合整表的條件就會 展示

*

如果換成右連結,那麼如果on中右表資料為空,那麼展示結果也會為空

*

如果on中左連接配接的左表條件為真,不影響查詢結果,如果為false,那麼右表的結果為空

繼續閱讀