显示来自MySQL查询的结果在LEFT JOIN中不存在

时间:2019-05-21 18:38:02

标签: mysql

我正在尝试从用户数据库请求与我的兴趣表中的任何条目都不匹配的记录。不幸的是,要么显示所有记录,要么不显示任何记录。

我尝试了多个mysql查询。

用户表

+------+-----------------+
| id   | username        |
+------+-----------------+
| 1200 | gordotheweirdo  |
| 1203 | emilly          |
| 1204 | belinda         |
| 1205 | dannbonadouchie |
+------+-----------------+

兴趣表

+-------------------+-------------------+------------------+
| p_interest_source | p_interest_target | p_interest_loser |
+-------------------+-------------------+------------------+
| 1204              | 1205              | 1200             |
+-------------------+-------------------+------------------+

我尝试过的简单语句。

select *
from users
left join interested
  on users.id = interested.p_interest_source
where interested.p_interest_source <> 1204
  AND interested.p_interest_target <> 1205;

在下表中,应该返回给用户表中除id 1205以外的所有用户,因为它们是在兴趣表中以1204为源的目标。

Empty set (0.00 sec)

2 个答案:

答案 0 :(得分:0)

尝试一下:

select *
from users
left join interested
  on users.id = interested.p_interest_source
where 
  interested.p_interest_source is null
  or interested.p_interest_source <> 1204 AND interested.p_interest_target <> 1205;

问题是您正在执行左联接,因此在不满足联接条件的每一行上,联接表的所有列中都有NULLNULL不等于也不等于其他值,因此对于这些行,此类条件永远不会成立:

interested.p_interest_target <> 1205 

答案 1 :(得分:0)

select u.*
from users u
left join interested i
  on  i.p_interest_target = u.id
  and i.p_interest_source = 1204
where i.p_interest_target is null

JOIN将在p_interest_target列中搜索用户ID的匹配项,但仅与其中p_interest_source = 1204的行匹配(请注意,此条件必须在ON子句中)。对于where i.p_interest_target is null,仅返回用户表中不匹配的行。

您还可以通过NOT EXISTS子查询获得相同的结果:

select u.*
from users u
where not exists (
  select *
  from interested i
  where i.p_interest_target = u.id
    and i.p_interest_source = 1204
)

db-fiddle demo

相关问题