mysql left join 左連接查詢關聯n多張表
阿新 • • 發佈:2017-06-02
part 存在 col 外鍵 ros bold new 多條 ble
left join 左連接即以左表為基準,顯示坐標所有的行,右表與左表關聯的數據會顯示,不關聯的則不顯示。關鍵字為left join on。
**基本用法如下:
select table a left join table b on a.id = b.ta_id**
註意:1??其中on後面關聯的字段應該是同一字段(兩表關聯的外鍵)
2??由於以左表為基準,左表一條記錄如果對應右表多條記錄,那查出的數據中右表的數據也只顯示一條,如果要都顯示,可以用group_contact()將字段用逗號隔開顯示在一條記錄上。所以右表不管有幾張,如果和左表都是一對一關系,則沒問題,存在一對多關系時,需要一定的處理。
三表關聯 則如下:
select table a left join table b(left join table c on b.id = c.tb_id) on a.id = b_ta.id
再拓展一下,如果關聯七八張表,就像下面這條sql,用法其實無非就像三表關聯一樣,一層套一層,只不過關系要理順好。
SELECT GROUP_CONCAT(u.stuffName), GROUP_CONCAT(ee.id), ee.applyTime, p.orderState, GROUP_CONCAT( concat( s.departureAirportCode,‘-‘, s.landingAirportCode ) ), p.pnr, sns.c, sns.b, sns.a, ee.pnr newp, GROUP_CONCAT( CONCAT( s.departureDate, ‘ ‘, s.departureTime ) ), GROUP_CONCAT(s.flightNum), GROUP_CONCAT(s.seatClass), c.rebookintSumFee, c.customerRebookintFee, c.amountReceivable, o.orderNum, comp.companycode, comp.companyNameFROM endrose ee LEFT JOIN passenger p ON ee.passengerId = p.id LEFT JOIN segment s ON s.endroseId = ee.id LEFT JOIN costfee c ON c.endroseId = ee.id LEFT JOIN( SELECT ns.passengerId, GROUP_CONCAT(ns.flightNum)b, GROUP_CONCAT(ns.seatClass)a, GROUP_CONCAT( CONCAT( ns.departureDate, ‘ ‘, ns.landingDate ) )c FROM segment ns WHERE ns.orderState = 0 GROUP BY ns.passengerId )sns ON sns.passengerId = ee.passengerId LEFT JOIN( passenger passe LEFT JOIN airticketorder o ON passe.orderId = o.id )ON passe.id = ee.passengerId LEFT JOIN( passenger pass LEFT JOIN `user` u ON pass.stuffUUID = u.id )ON pass.id = ee.passengerId LEFT JOIN( passenger passen LEFT JOIN( airticketorder ao left join( `user` ua left join company comp on comp.id = ua.companyId )ON ao.bookerstuffId = ua.id ) ON passen.orderId = ao.id ) ON passen.id = ee.passengerId group by ee.applyTime
這條sql中尤其是最後一個left join,關聯了好幾張表,要好好理順才行。
寫的時候從外層往裏寫,一層一層left join,才不容易出錯。
http://www.cnblogs.com/amyStart/p/5965472.html
mysql left join 左連接查詢關聯n多張表