首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >显示左连接中不存在的Mysql查询结果

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

Stack Overflow用户
提问于 2019-05-22 02:38:02
回答 2查看 28关注 0票数 1

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

我已经尝试了多个mysql查询。

用户表

代码语言:javascript
复制
+------+-----------------+
| id   | username        |
+------+-----------------+
| 1200 | gordotheweirdo  |
| 1203 | emilly          |
| 1204 | belinda         |
| 1205 | dannbonadouchie |
+------+-----------------+

利息表

代码语言:javascript
复制
+-------------------+-------------------+------------------+
| p_interest_source | p_interest_target | p_interest_loser |
+-------------------+-------------------+------------------+
| 1204              | 1205              | 1200             |
+-------------------+-------------------+------------------+

简单的声明我试过了。

代码语言:javascript
复制
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;

在下面的表中,我应该返回的是user表中除id 1205之外的所有人,因为他们是在Interest table中找到的目标,其中1204是源。

代码语言:javascript
复制
Empty set (0.00 sec)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-22 02:58:00

代码语言:javascript
复制
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

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

您也可以使用NOT EXISTS子查询获得相同的结果:

代码语言:javascript
复制
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

票数 0
EN

Stack Overflow用户

发布于 2019-05-22 02:54:54

试试这个:

代码语言:javascript
复制
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;

问题是您正在进行左连接,所以在不满足连接条件的每一行上,在连接的表的所有列中都有NULL。并且NULL既不等于也不等于其他值,因此对于这些行,这样的条件永远不会成立:

代码语言:javascript
复制
interested.p_interest_target <> 1205 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56244512

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档