gpt4 book ai didi

mysql - 显示 LEFT JOIN 中不存在的 Mysql 查询结果

转载 作者:行者123 更新时间:2023-11-30 21:30:51 25 4
gpt4 key购买 nike

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

我尝试了多个 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)

最佳答案

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

关于mysql - 显示 LEFT JOIN 中不存在的 Mysql 查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56244512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com