mysql - sql查询数据全部存在

标签 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。

最佳答案

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

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/

相关文章:

sql - 不区分大小写的搜索/查询

MySql 插入两个用外键连接的表

php - 如何制作由 Google 索引为静态页面的 PHP/Cakephp 数据库驱动页面

php - 在 CakePHP 中按 1 更新行

mysql - 我可以强制MySQL在查询完成之前输出结果吗?

java.sql.SQLException : Access denied for user 'root' @'localhost' . 无法创建与数据库服务器的连接

mysql - -bash : ./配置 : No such file or directory - MySQL install on Mac OS X 10. 6

mysql - 如何在mysql中将动态ID与选择查询结合起来

SQL UPDATE 在设置前读取列值

php - 在 cakephp 中将数据从 javascript 传递到 PHP