我有两张桌子:
interests (storing the interest ID and name)
person_interests(storing the person_id and interest_id)
如何选择特定人士未选择的所有兴趣?
我尝试了以下SQL查询,但仍未获得所需的结果
SELECT *
FROM interests LEFT JOIN person_interests
ON interests.id=person_interests.person_id
WHERE person_interests.id IS NULL
AND person_id=66;
答案 0 :(得分:3)
使用NOT EXISTS
SELECT *
FROM interests
WHERE NOT EXISTS (
SELECT person_interests.interest_id
FROM person_interests
WHERE person_id = 66
AND interests.id = person_interests.interest_id
)
答案 1 :(得分:0)
SELECT * from interests
WHERE interest_id NOT IN
(SELECT interest_id FROM person_interests WHERE person_id=66)
答案 2 :(得分:0)
有几件事正在发生。
首先,我认为您的加入时出错了。不应该是interests.id=person_interests.interest_id
而不是interests.id=person_interests.person_id
吗?
除此之外,我仍然认为你没有得到想要的结果,因为你的person_id过滤器位于左外连接的右侧,因此将其转回内部连接。有几种方法可以解决这个问题。这就是我可能会做的事情:
SELECT *
FROM
(SELECT interests.*, person_id
FROM interests LEFT JOIN person_interests
ON interests.id=person_interests.interest_id
WHERE person_interests.id IS NULL )
WHERE person_id=66;