SQL:获取null作为不匹配查询的行的返回值

时间:2015-07-03 11:55:05

标签: php mysql sql

我有一张表Entity和一张表Friends。我想获取访问过相同位置的人的姓名,但如果他们不是该人的朋友(建议的朋友查询),我只想返回他们。为了做到这一点,我写了以下查询:

SELECT Entity_Id,
       Category AS FC
 FROM  entity
 LEFT 
 JOIN  friends 
   ON  entity.Entity_Id = friends.Entity_Id1 
   OR  entity.Entity_Id = friends.Entity_Id2
WHERE  Entity_Id IN ( :list_of_ids ) 
  AND  Entity_Id != :user_id
  AND  Category != 4
GROUP 
   BY  Entity_Id

:list_of_ids是逗号分隔的用户ID列表,在我的测试查询中有82个用户,但查询只返回15个用户,返回的用户是与以下人员有关系的用户:user_id 。

查询中不会返回表中没有关系的任何用户。我想通过提供LEFT OUTER JOIN它会为在friends表中找不到的字段返回NULL。

----- EXPECTED -----
--------------------
Entity_Id         FC
--------------------
1                  3
2                  2
3                  2
4               null
52              null
64              null

------ ACTUAL -------
---------------------
Entity_Id          FC
---------------------
1                  3
2                  2
3                  2

我朋友表的结构如下,同时请注意,如果有任何帮助,它支持互惠关系......

------ FRIENDS ------
---------------------
fid                PK
entity_id1        INT
entity_id2        INT
category          INT  -- 1 = Facebook, 2 = G+, 3 = App, 4 = Blocked

如何归还关系丢失的用户?

2 个答案:

答案 0 :(得分:3)

你想要一个left outer join。但是,对于left join,第二个表上的条件需要进入on子句:

SELECT e.Entity_Id, f.Category AS FC
FROM entity e LEFT JOIN
     friends f
     ON e.Entity_Id IN (f.Entity_Id1, f.Entity_Id2) AND
        f.category <> 4
WHERE e.Entity_Id IN ( :list_of_ids ) AND
      e.Entity_Id <> :user_id
GROUP BY e.Entity_Id;

如果category子句中的条件为WHERE,则会将LEFT JOIN变为INNER JOIN。如果没有匹配项,category的值为NULL,则无法进行比较。

答案 1 :(得分:1)

该类别属于哪个表?如果是朋友列,请将Category != 4WHERE移至ON以获得真正的外部联接。 (否则它作为常规的内部连接执行...):

SELECT Entity_Id, Category AS FC
FROM  entity
 LEFT JOIN  friends 
   ON  (entity.Entity_Id = friends.Entity_Id1 
        OR entity.Entity_Id = friends.Entity_Id2)
   AND Category != 4
WHERE  entity.Entity_Id IN ( :list_of_ids ) 
  AND  entity.Entity_Id != :user_id
GROUP 
   BY  Entity_Id