Dre*_*rew 3 mysql sql database
我有一张桌子,看起来像:
+-----------+----------+
+ person_id + group_id +
+-----------+----------+
+ 1 + 10 +
+ 1 + 20 +
+ 1 + 30 +
+ 2 + 10 +
+ 2 + 20 +
+ 3 + 10 +
+-----------+----------+
Run Code Online (Sandbox Code Playgroud)
我需要一个查询,只返回组10和20和30的person_ids(只有person_id:1).我不知道如何做到这一点,因为我可以看到它需要我按person_id对行进行分组,然后选择包含所有group_id的行.
我正在寻找一些能够保留密钥使用而不需要依赖字符串操作的东西group_concat().
分组和点击次数:
select person_id
from ATable
where group_id IN (10, 20, 30)
group by person_id
having count(*) = 3
Run Code Online (Sandbox Code Playgroud)
这就是你要找的东西:
select person_id from t
where group_id in (10, 20, 30)
group by person_id
having count(distinct group_id) = 3
Run Code Online (Sandbox Code Playgroud)
虽然效率很高,但使用此解决方案时,数量中的值in必须与您比较计数的值相匹配.
正如你所说的那样,即便与group_concat你一起解决这个问题:P
select person_id from t
where group_id in (10, 20, 30)
group by person_id
having group_concat(distinct group_id order by group_id) = '10,20,30'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |