9

我的目标是完全按照 LEFT OUTER JOIN 使用第四个维恩图来做的事情:SQL 图表

在此处输入图像描述

我的查询根本没有返回任何值,实际上,它应该返回 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 用于演示目的,以尝试挑选正确的行。

4

2 回答 2

19

您当前的查询基本上是INNER JOIN由于consultant_id = 5onWHERE子句而执行的。我相信您实际上想使用:

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

于 2013-02-13T20:01:19.407 回答
3

采用

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 子句忽略了左外连接。

于 2013-02-13T20:06:31.613 回答