过滤加入的结果

时间:2017-06-14 13:20:49

标签: mysql database

想象一下下面的表结构:

tb.user     tb.usergroups   tb.group
id          id              id
name        user_id         name
            group_id        

user可以通过usergroups表格分成多个组。

我想按用户名和组名搜索用户。在例子中说:用户" Bob"在" GroupA"并在" GroupB"。我的询问到目前为止:

SELECT *
FROM user u
JOIN usergroups ug ON ug.user_id = u.id
JOIN group g ON ug.group_id = g.id
WHERE u.name = 'Bob' AND g.name != 'GroupA'

这不是我想要的;我的结果仍然包含鲍勃,因为他在" GroupB",但我不希望结果包含鲍勃。

怎么做?

由于

2 个答案:

答案 0 :(得分:0)

我知道您要选择名为“Bob”的所有用户,这些用户不属于A组但属于B组。这应该这样做:

SELECT b.*
FROM (SELECT * FROM user u
JOIN usergroups ug ON ug.user_id = u.id
JOIN group g ON ug.group_id = g.id
WHERE u.name = 'Bob' AND g.name = 'GroupB') b
LEFT JOIN  (SELECT userid FROM user u
JOIN usergroups ug ON ug.user_id = u.id
JOIN group g ON ug.group_id = g.id
WHERE u.name = 'Bob' AND g.name = 'GroupA') a
ON a.userid=b.userid
WHERE a.userid is NULL

答案 1 :(得分:0)

检查此查询,因为我知道您看起来像这样:

SELECT * FROM user AS u
LEFT JOIN usergroups AS ug ON u.id = ug.user_id
LEFT JOIN groups AS gp ON gp.id = ug.group_id
WHERE u.name = 'Bob'
GROUP by ug.user_id
HAVING count(ug.group_id) = 1 AND gp.name !="GROUPA"