所有的SQL查询数据都存在

时间:2015-04-14 07:58:09

标签: mysql sql cakephp cakephp-1.3

我有用户和角色表。用户有多重角色......

user table - id, username

manageroles table - id, user_id, role_id

roles table - id, rolename

假设用户a有role_id = 1和2

假设用户b有role_id = 2和3

测试用例 -

1- want user of roleid 2-----output- a,b
2- want user of roleid 1,2-----output- a
3- want user of roleid 2,3-----output- b

请建议单sql查询以获得此类输出。我正在使用cakephp 1.3和mysql 5.6。

1 个答案:

答案 0 :(得分:1)

由于您将数据存储在一对多关系中,因此第一个查询将很简单

select * from table_name 
where role_id = 2;

1,2

select user_id from table_name 
where role_id in (1,2)
group by user_id having count(Distinct role_id) = 2 ;

2,3

select user_id from table_name 
where role_id in (2,3)
group by user_id having count(Distinct role_id) = 2 ;