我正在尝试从用户数据库请求与我的兴趣表中的任何条目都不匹配的记录。不幸的是,要么显示所有记录,要么没有显示任何记录。
我已经尝试了多个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;
在下面的表中,我应该返回的是user表中除id 1205之外的所有人,因为他们是在Interest table中找到的目标,其中1204是源。
Empty set (0.00 sec)
发布于 2019-05-22 02:58:00
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子查询获得相同的结果:
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
)
发布于 2019-05-22 02:54:54
试试这个:
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
既不等于也不等于其他值,因此对于这些行,这样的条件永远不会成立:
interested.p_interest_target <> 1205
https://stackoverflow.com/questions/56244512
复制相似问题