LEFT OUTER JOIN查询不返回预期的行

时间:2013-02-13 19:56:39

标签: mysql left-join sqlfiddle

我的目标是使用第4个维恩图来完成LEFT OUTER JOIN打算做的事情:SQL Diagrams

enter image description here

我的查询根本没有返回任何值,实际上,它应该返回Consultant_Memberships中的所有值减去Consultant_Memberships_Lists中存储的值。

请参阅SQL Fiddle以便更加了解:

SELECT * 
FROM   consultant_memberships 
       LEFT OUTER JOIN consultant_memberships_list 
                    ON consultant_memberships.`id` = 
                       consultant_memberships_list.membership_id 
WHERE  consultant_memberships_list.consultant_id = $id 
       AND consultant_memberships_list.membership_id IS NULL 

查询使用'5'作为ID用于演示目的,以尝试选择正确的行。

2 个答案:

答案 0 :(得分:15)

由于INNER JOIN子句上的consultant_id = 5,您当前的查询基本上正在执行WHERE。我相信你真的想用:

SELECT * 
FROM   consultant_memberships m
LEFT OUTER JOIN consultant_memberships_list l
  ON m.`id` = l.membership_id 
  AND l.consultant_id = 5 
WHERE l.membership_id IS NULL;

请参阅SQL Fiddle with Demo

答案 1 :(得分:2)

使用

SELECT * 
   FROM   consultant_memberships 
       LEFT  Outer JOIN consultant_memberships_list 
                ON consultant_memberships_list.membership_id = consultant_memberships.`id`  
                and  consultant_memberships_list.consultant_id = 5 
 where  consultant_memberships_list.membership_id IS NULL;

在查询“consultant_memberships_list.consultant_id = 5”之前使用的Where子句忽略了左外连接。