MySQL LEFT JOIN来自同一源表的多个表

时间:2012-12-20 18:05:10

标签: mysql

我有以下表格:

companyContacts
addresses
states
phoneNumbers

我需要在addressesstatesphoneNumbers上进行LEFT JOIN。我需要将phoneNumbersaddressescompanyContacts联系起来,并且需要将statesaddresses联系起来。

我可以选择以下内容来抓取所有内容。但是,如果有人有地址而不是电话号码,则不会返回结果。我该如何制作phoneNumbersaddresses以及companyContacts加入?

SELECT * FROM
    companyContacts AS c
    LEFT JOIN phoneNumbers AS p
        ON c.entityID = p.entityID
    LEFT JOIN addresses AS a
        ON p.entityID = a.entityID
    LEFT JOIN states AS s
        ON a.stateID = s.id

1 个答案:

答案 0 :(得分:3)

听起来你想要这个:

SELECT * 
FROM  companyContacts AS c
LEFT JOIN phoneNumbers AS p
   ON c.entityID = p.entityID
LEFT JOIN addresses AS a
   ON c.entityID = a.entityID
LEFT JOIN states AS s
   ON a.stateID = s.id

如果您companyContacts.entityId加入phoneNumbersaddresses,即使没有电话号码或地址,您也会返回记录。你用它写的方式需要存在的电话号码才能返回地址