【问题标题】:Sql query data exist in allsql查询数据全部存在
【发布时间】:2015-06-19 17:57:34
【问题描述】:

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

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。

【问题讨论】:

  • 你把数据保存为逗号分隔?
  • 在mysql的子句中使用。
  • 这只是示例....列是 user_id 和 role_id...对于一个用户有多个条目...
  • 您最好以正确的列格式向我们展示(样本)表格数据。

标签: mysql sql cakephp cakephp-1.3


【解决方案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 ;

【讨论】:

  • 是的,它会解决我的问题..但是如果在这种情况下有多个条目..多个条目意味着同一行被错误地插入了两次......它可能会返回错误的输出......
  • 是的,如果有多个条目,即超过 2 个,则条件为 having count(distinct role_id) = 2,但如果您的角色 ID 与 in 子句中的不同,则您可以使用 >=2跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多