db查询返回条件1 = true或condition2 = true时的记录,但当condition1和condition2 = true一起时不返回记录

时间:2019-03-22 14:14:23

标签: mysql

user | manager | permission
-------------------------
adam    john         1
adam    john         2
adam    john         4
dave    john         1
dave    john         2
dave    john         3
dave    john         4
ben     rick         3
ben     rick         4
ben     rick         5
ed      susan        2
ed      susan        3
carl    susan        1
carl    susan        4
nancy   peter        3
nancy   peter        4

我想要一个查询,该查询将返回用户具有2的权限,但没有3或具有3的权限,但没有2的权限,但我不想让用户同时拥有2和3的权限以及没有2和3的用户。

user
----- 
adam 
ben
nancy  

2 个答案:

答案 0 :(得分:0)

您可以group by user并进行检查,以使最大和最小权限等于2或3:

select user from tablename
where permission in (2,3)
group by user
having 
  (min(permission) = 2 and max(permission) = 2)
  or
  (min(permission) = 3 and max(permission) = 3)

答案 1 :(得分:0)

如果您针对拥有2或3权限的用户进行过滤,则可以分组并针对在2,3中只有一个权限的人员进行过滤

SELECT
    user
FROM table
WHERE permission IN (2, 3)
GROUP BY USER
HAVING COUNT(permission) = 1;