加入如果存在于MySQL查询中

时间:2011-06-08 13:40:33

标签: mysql sql join

我正在运行一份报告,将委员会成员的信息导出到Excel电子表格中。

这是我的疑问:

SELECT membership_organization.name AS Firm, 
membership_individual.first AS FirstName, 
membership_individual.middle AS MiddleName, 
membership_individual.last AS LastName, 
membership_individual.email AS Email, 
membership_individual.phone AS Phone, 
membership_location.addr1 AS Address1, 
membership_location.addr2 AS Address2, 
membership_location.city AS City, 
membership_location.state AS State, 
membership_location.zipcode AS Zip 
FROM membership_individual 
JOIN membership_organization ON membership_individual.org_name_id = membership_organization.id 
JOIN membership_location ON membership_individual.location_id = membership_location.id 
WHERE membership_individual.id IN ({list if ids}) 
ORDER BY LastName

问题是某些成员没有设置位置ID,或者设置为0,因此这些成员不会显示在报告中。

有没有办法让我有资格获得位置JOIN?如果成员位置ID存在,请拉取信息,如果没有显示可用的信息。

4 个答案:

答案 0 :(得分:29)

JOIN更改为LEFT JOIN s。您将从与where子句匹配的membership_individual获取所有记录,并为行不匹配的其他表获取NULL值。

答案 1 :(得分:4)

使用LEFT OUTER JOIN:

SELECT membership_organization.name AS Firm, 
membership_individual.first AS FirstName, 
membership_individual.middle AS MiddleName, 
membership_individual.last AS LastName, 
membership_individual.email AS Email, 
membership_individual.phone AS Phone, 
membership_location.addr1 AS Address1, 
membership_location.addr2 AS Address2, 
membership_location.city AS City, 
membership_location.state AS State, 
membership_location.zipcode AS Zip 
FROM membership_individual 
JOIN membership_organization ON membership_individual.org_name_id = membership_organization.id 
LEFT OUTER JOIN membership_location ON membership_individual.location_id = membership_location.id 
WHERE membership_individual.id IN ({list if ids}) 
ORDER BY LastName

答案 2 :(得分:0)

尝试使用

LEFT JOIN membership_location ON membership_individual.location_id = membership_location.id 

而不是你的变种..

答案 3 :(得分:0)

使用左连接,意味着您的查询将变为

SELECT membership_organization.name AS Firm, 
membership_individual.first AS FirstName, 
membership_individual.middle AS MiddleName, 
membership_individual.last AS LastName, 
membership_individual.email AS Email, 
membership_individual.phone AS Phone, 
membership_location.addr1 AS Address1, 
membership_location.addr2 AS Address2, 
membership_location.city AS City, 
membership_location.state AS State, 
membership_location.zipcode AS Zip 
FROM membership_individual 
JOIN membership_organization ON membership_individual.org_name_id = membership_organization.id 
LEFT JOIN membership_location ON membership_individual.location_id = membership_location.id 
WHERE membership_individual.id IN ({list if ids}) 
ORDER BY LastName

您将获得所有成员的数据,甚至是位置表中没有行的成员。