显示左联接中不存在的Mysql查询结果

显示左联接中不存在的Mysql查询结果,mysql,Mysql,我试图从用户数据库中请求与我的兴趣表中的任何条目都不匹配的记录。不幸的是,要么显示所有记录,要么不显示任何记录 我尝试了多个mysql查询 用户表 +------+-----------------+ | id | username | +------+-----------------+ | 1200 | gordotheweirdo | | 1203 | emilly | | 1204 | belinda | | 1205 | dannb

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

我尝试了多个mysql查询

用户表

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

+-------------------+-------------------+------------------+
| p_interest_source | p_interest_target | p_interest_loser |
+-------------------+-------------------+------------------+
| 1204              | 1205              | 1200             |
+-------------------+-------------------+------------------+
我试过的简单陈述

挑选* 来自用户 左加入感兴趣 on users.id=interest.p\u interest\u source 有兴趣的地方。p_兴趣来源1204 和感兴趣。p_兴趣_目标1205; 在下表中,应该为我返回的是用户表中除id 1205之外的所有人,因为他们在兴趣表中作为目标找到,1204是源

Empty set (0.00 sec)
试试这个:

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;
试试这个:

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;
联接将在p_interest_target列中搜索用户ID的匹配项,但仅搜索行,其中p_interest_source=1204请注意,此条件必须在ON子句中。如果i.p_interest_target为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
)
联接将在p_interest_target列中搜索用户ID的匹配项,但仅搜索行,其中p_interest_source=1204请注意,此条件必须在ON子句中。如果i.p_interest_target为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
)

通过该查询,用户1205将始终显示;但是,该查询将忽略1204以1205为目标的任何结果。。。如果1204以1205为目标且仅为1205,则将完全忽略1204。还请记住,没有特殊处理的空比较将评估为空;因此,您的条件将您的左连接变成内部连接,这就是为什么您无法在结果中获得其他用户的原因;但是,该查询将忽略1204以1205为目标的任何结果。。。如果1204以1205为目标且仅为1205,则将完全忽略1204。还请记住,没有特殊处理的空比较将评估为空;因此,您的条件会将左连接变成内部连接,这就是为什么您不能在结果中获得其他用户的原因。@forpas No。。我编辑了操作码。使用u和i作为别名是显而易见的。不,你用小提琴编辑了我的答案。我现在恢复了健康。请看我答案中编辑的内容。@forpas我现在明白你的意思了。对不起-别担心。我修复了它。@forpas没有。。我编辑了操作码。使用u和i作为别名是显而易见的。不,你用小提琴编辑了我的答案。我现在恢复了健康。请看我答案中编辑的内容。@forpas我现在明白你的意思了。对不起-别担心。我修复了它。