首页 > 代码库 > mysql left join 左连接查询关联n多张表

mysql left join 左连接查询关联n多张表

eft 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.companyName
FROM
    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,才不容易出错。

mysql left join 左连接查询关联n多张表