MySQL GROUP BY“和过滤器”

前端之家收集整理的这篇文章主要介绍了MySQL GROUP BY“和过滤器”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

假设我有这样的查询

SELECT name,GROUP_CONCAT(number)
FROM objects
GROUP BY name

输出

+----------+----------------------+
|  NAME    | GROUP_CONCAT(NUMBER) |
+----------+----------------------+
| false_1  | 2,1                  |
| false_2  | 3,4                  |
| true_1   | 4,3,2,1              |
| true_2   | 2,3                  |
+----------+----------------------+

现在我如何返回2和3作为数字的行?

注意:此查询已分组 – 表有10行,如下所示:

+---------+--------+
|  NAME   | NUMBER |
+---------+--------+
| true_1  | 1      |
| true_1  | 2      |
| true_1  | 3      |
| ...     | ...    |
+---------+--------+

[Link to SQLFiddle]

最佳答案
SELECT name,GROUP_CONCAT(number)
FROM objects
WHERE number IN (2,3)
GROUP BY name
HAVING COUNT(*) = 2

> SEE SQLFiddle Demo

或者如果要保留名称所具有的所有值,

SELECT  a.name,GROUP_CONCAT(A.number)
FROM    objects a
        INNER JOIN
        (
          SELECT name
          FROM objects
          WHERE number IN (2,3)
          GROUP BY name
          HAVING COUNT(*) = 2
        ) b ON a.Name = b.Name
GROUP BY a.name

> SEE SQLFiddle Demo

原文链接:https://www.f2er.com/mysql/433435.html

猜你在找的MySQL相关文章