我有NighClub,Visitor和Visitors_NighClub表(很多)。 我需要获得所有没有某些访客的夜总会。
要让某些访客拥有NightClub,我喜欢这样:
id
但是如何让整夜没有一定访客的俱乐部。我不能喜欢:
link
答案 0 :(得分:0)
您可以尝试使用相关子查询
SELECT nc.id, nc.name
FROM night_club as nc
INNER JOIN visitor_night_clubs as vnc ON nc.id = vnc.night_clubs_id
WHERE not exists
(select 1 from visitor_night_clubs as vnc1 where vnc.night_clubs_id=vnc1.night_clubs_id and vnc1.visitors_id=3)
答案 1 :(得分:0)
禁止使用
SELECT nc.id, nc.name
FROM night_club as nc
INNER JOIN visitor_night_clubs as vnc ON nc.id = vnc.night_clubs_id
WHERE vnc.visitors_id not in( 3,....)
答案 2 :(得分:0)
找出答案
SELECT *
FROM night_club
WHERE night_club.id NOT IN
(SELECT nc.id
FROM night_club as nc
INNER JOIN visitor_night_clubs as vnc ON nc.id = vnc.night_clubs_id
WHERE vnc.visitors_id = 4)
答案 3 :(得分:0)
为此,我推荐not exists
:
select nc.*
from night_club nc
where not exists (select 1
from visitor_night_clubs vnc
where vnc.night_clubs_id = nc.id and
vnc.visitors_id = 4
);
为什么NOT EXISTS
比NOT IN
好?原因很简单:当子查询返回的任何值为NOT IN
时,NULL
不会达到您的期望。这只会使使用变得危险。尽管您可以过滤掉NULL
的值,但是始终使用NOT EXISTS
意味着这永远不会成为问题。
还请注意使用表别名,并且子查询中不需要JOIN
。