SELECT如果左连接IS AND IS NOT(MYSQL)?

时间:2015-03-24 07:48:31

标签: mysql select join

我有一张桌子"人物"。

另一个" hobbiesConnection",它们作为OneToMany连接。

我想建立一个搜索,在那里可以搜索有业余爱好并且没有兴趣的人。

类似的东西:

SELECT * FROM people
LEFT JOIN hobbiesConnection ON hobbiesConnection.people_id = 
hobbiesConnection.hobby_id
WHERE hobby_id = 4 AND hobby_id != 5

现在我得到了爱好者4,但我希望得到一个空洞的结果,因为这两个条件都必须适合这个人。

有人知道如何做到这一点吗?

2 个答案:

答案 0 :(得分:0)

首先,您的 JOIN 不正确。这两个表应该与外键/公共列链接。请尝试以下查询;

SELECT * FROM people
LEFT JOIN hobbiesConnection 
ON hobbiesConnection.people_id = people.people_id
And (hobbiesConnection.hobby_id = 4 AND hobbiesConnection.hobby_id != 5)

答案 1 :(得分:-1)

使用(NOT)EXISTS条款:

SELECT * FROM people p
WHERE TRUE
AND EXISTS (
  SELECT TRUE FROM hobbiesConnection hc 
  WHERE hc.people_id = p.people_id -- or p.id? you didnt mention
  AND hobby_id = 4
)
AND NOT EXISTS (
  SELECT TRUE FROM hobbiesConnection hc 
  WHERE hc.people_id = p.people_id -- or p.id? you didnt mention
  AND hobby_id = 5
)

使用连接

可以实现相同的效果
SELECT p.* 
FROM people p
JOIN hobbiesConnection h4 ON TRUE
    AND h4.people_id = p.people_id -- or p.id? you didnt mention
    AND h4.hobby_id = 4
LEFT JOIN hobbiesConnection h5 ON TRUE
    AND h5.people_id = p.people_id -- or p.id? you didnt mention
    AND h5.hobby_id = 5
WHERE h5.id IS NULL -- or whatever column from that table

看看小提琴:http://sqlfiddle.com/#!9/d9926/4