展开GROUP BY和HAVING结果集

时间:2011-08-23 17:49:13

标签: mysql group-by having

有没有办法展开/获取GROUP BYHAVING查询的所有记录?

例如,

SELECT Column1, Column2, Column3, Count(*) as Count FROM table_name
GROUP BY Column1, Column2, Column3
HAVING Count > '2'

是否有更简单的方法来获取所有记录,而不是遍历结果集并为每条记录执行SELECT * FROM table_name WHERE Column1 = 'this' AND Column2 = 'that' AND Column3 = 'more'

如果由于mysql或其他一些限制而无法完成,是否有其他方法可以获取上面query的所有数据?

通过展开/获取所有记录,我的意思是结果集是

Value1 Value2 Value3 4

我希望能够获得所有4条记录。

1 个答案:

答案 0 :(得分:5)

你的意思是这样的:

SELECT a.*, b.Count
FROM table_name AS a
INNER JOIN (
    SELECT Column1, Column2, Column3, Count(*) as Count FROM table_name
    GROUP BY Column1, Column2, Column3
    HAVING Count > '2'
) b
ON a.Column1 = b.Column1 AND a.Column2 = b.Column2 AND a.Column3 = b.Column3

这基本上就是您在问题中所描述的内容,而是JOIN