我有用户和角色表。用户具有多个角色....
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。
最佳答案
由于您以一对多关系存储数据,第一个查询将很简单
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 ;
关于mysql - sql查询数据全部存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29622009/