选择依赖于计算两列

时间:2017-03-11 16:33:34

标签: mysql

我从数据库中选择了这种表:

user project role 
XXX  p1      admin 
XXX  p2      developer 
xxx  p1      developer 
yyy  p3      tester 
yyy  p1      developer 
yyy  p1      admin 
zzz  p2      developer 

我需要添加到此查询过滤器:如果用户在一个项目中至少有两个角色。

我该怎么做?在这种情况下,MySQL的功能可以帮到我什么?

1 个答案:

答案 0 :(得分:1)

GROUP BY项目并添加HAVING子句以限制COUNT> 1

SELECT user, project, count(*) AS number_of_roles
FROM thetable
GROUP BY project
HAVING count(*) > 1

奖励:聚合了所有角色的列

SELECT user, project, count(*) AS number_of_roles, GROUP_CONCAT(role) AS roles  
FROM thetable
GROUP BY project
HAVING count(*) > 1