單個left join:
(1)一對一:結果表的行數=左表行數
(2)一對多:結果表的行數>左表行數
多個left join:
(0)多個left join由上到下,依次生成查詢表,原理同單個left join
(1)需要補充的是,如果在left join a表之前,想先對a表做一個字段的篩選,不能在多個left join之后用where來條件過濾,因為,多個left join是優先於where執行的,如果用where是對多個left join之后的結果查詢表進行的條件過濾。(這種很容造成結果錯誤,也就是結果數據不全)
應該用,left join ON 后+"and"去先過濾
a left join b ON a.id=b.id and a.isdel =0 b.status =1
left join c ON a.id =c.id and c.type=3
PS:有時候,單個left join、多個left join 需要跟select配合套多個"select馬甲"使用,下邊是一個很不錯的常用模版套法:
(一般對於不知道什么時候起別名 什么時候用括號的老鐵們 真實頭疼 所以發個模板,可以根據自己的需求,進行套用)
https://www.cnblogs.com/LHWorldBlog/p/7753914.html
不多說 直接上語句
SELECT
a.id,
a.thumbNail,
a. NAME,
a.marketPrice,
a.memberPrice,
a.personName,
a. STATUS,
a.recieveOrderDate,
a.trackNumber,
a.contact,
a.reportSendDate,
b.trackNumber,
a.reportDownloadPath
FROM
(
SELECT
od.id,
ps.thumbNail,
ps. NAME,
od.marketPrice,
od.memberPrice,
od.personName,
od. STATUS,
od.recieveOrderDate,
ol.trackNumber,
ol.contact,
od.reportSendDate,
od.reportSendOrderLogisticId,
od.reportDownloadPath
FROM
orders.order_detail od
LEFT JOIN orders.order_logistics ol ON od.recieveOrderLogisticId = ol.id
LEFT JOIN orders.product_snapshot ps ON od.productSnapShotId = ps.id
WHERE
od.valid = TRUE
AND ol.valid = TRUE
AND od.orderId =?
) a
LEFT JOIN (
SELECT
ol.trackNumber,
od.id
FROM
orders.order_detail od
LEFT JOIN orders.order_logistics ol ON od.reportSendOrderLogisticId = ol.id
WHERE
od.valid = TRUE
AND ol.valid = TRUE
AND od.orderId =?
) b ON a.id = b.id