gpt4 book ai didi

mysql - 如何对行组执行 'WHERE'?

转载 作者:可可西里 更新时间:2023-11-01 07:50:01 26 4
gpt4 key购买 nike

我有一张 table ,它看起来像:

+-----------+----------+
+ person_id + group_id +
+-----------+----------+
+ 1 + 10 +
+ 1 + 20 +
+ 1 + 30 +
+ 2 + 10 +
+ 2 + 20 +
+ 3 + 10 +
+-----------+----------+

我需要一个查询,以便只返回具有组 10 和 20 和 30 的 person_id(仅 person_id:1)。我不确定如何执行此操作,因为据我所知,这需要我按 person_id 对行进行分组,然后选择包含所有 group_id 的行。

我正在寻找可以保留键的使用而无需诉诸 group_concat() 等字符串操作的东西。

最佳答案

这就是您要找的:

select person_id from t
where group_id in (10, 20, 30)
group by person_id
having count(distinct group_id) = 3

虽然高效,但使用此解决方案时,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'

关于mysql - 如何对行组执行 'WHERE'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10166954/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com