基于公共ID

时间:2017-09-05 18:33:53

标签: mysql outer-join

我正在尝试运行一个查询,该查询显示不属于其中一个组的客户的所有成员。我正在比较两个具有共同CustomerID并使用其成员ID的表来显示哪些成员不在第二个表CustomerGroupMember中。

以下是两个表的示例。

客户会员

    id  | CustomerID | First | Last
    ---------------------------------
    123 | 1234       | Jim   | Sample
    129 | 1234       | Julie | Clark
    137 | 1234       | Jack  | Thomas
    289 | 1234       | Sue   | Smith

客户群成员

    MemberID  | CustomerID | GroupID
    ---------------------------------
    129       | 1234       | 19
    289       | 1234       | 20

以下是我的查询似乎没有产生任何结果。我希望输出在该Customer Group Member表中找不到的任何人。在上面的表格示例中,我将看到成员123和137的输出。

SELECT CustomerMember.* FROM CustomerMember 
LEFT JOIN
 CustomerGroupMember ON CustomerMember.id = CustomerGroupMember.MemberID 
WHERE 
CustomerMember.CustomerID = '1234' AND CustomerGroupMember.CustomerID = '1234' 
AND CustomerGroupMember.MemberID IS NULL

1 个答案:

答案 0 :(得分:1)

使用第二个条件(CustomerGroupMember.CustomerID = '1234'),您将LEFT JOIN转换为INNER JOIN。将过滤掉CustomerGroupMember列中具有NULL的所有行,因为NULL不能等于'1234'。您需要将该条件移动到ON子句中:

SELECT CustomerMember.* FROM CustomerMember 
LEFT JOIN
 CustomerGroupMember 
 ON CustomerMember.id = CustomerGroupMember.MemberID 
 AND CustomerGroupMember.CustomerID = '1234'
WHERE 
CustomerMember.CustomerID = '1234'  
AND CustomerGroupMember.MemberID IS NULL;

http://rextester.com/DLTQ86207