【问题标题】:How do I perform 'WHERE' on groups of rows?如何在行组上执行“WHERE”?
【发布时间】:2012-04-16 23:07:00
【问题描述】:

我有一张桌子,看起来像:

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

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

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

【问题讨论】:

  • WHERE group_id IN (10, 20, 30)
  • @kirilloid,这仍然会返回所有的人
  • 我明白了你的想法。 AFAIK,只有这样:使用多个 JOIN

标签: mysql sql database


【解决方案1】:

这就是你要找的:

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'

【讨论】:

  • 谢谢 :) 我希望你不是在谈论 group_concat 的东西 :P
  • ;-) 不同的 group_id 对零维护查询至关重要。
  • 是的,我会跳过 group_concat()。 :-P 但这是最​​好的情况。星期五花了 4 个小时试图解决它。在火车上上班的路上问问题,在我上班之前,问题就解决了。是的,我把功劳归功于 SO。 :-)
【解决方案2】:

对点击进行分组和计数:

select person_id
  from ATable
 where group_id IN (10, 20, 30)
 group by person_id
having count(*) = 3

【讨论】:

    【解决方案3】:
    SELECT person_id FROM... WHERE group_id IN(10,20,30) group by person_id
    having count(*) = 3
    

    【讨论】:

    • 这将对 group_id 执行 OR
    • 啊,对不起,您只希望它在 person_id = 1 好的地方得到它 SELECT person_id FROM... WHERE person_id = 1 AND WHERE group_id IN(10,20,30)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    相关资源
    最近更新 更多