MYSQL Group通过Count订购?

时间:2011-04-19 19:53:52

标签: mysql group-by mysql-error-1140

我正在尝试做类似于Select the 3 most recent records where the values of one column are distinct的事情,但有一个计数,这意味着我需要保留该组。

使用相同的例子:

 id       time      text      otheridentifier
-------------------------------------------
1        6         apple     4
2        7         orange    4
3        8         banana    3
4        9         pear      3
5        10        grape     2

SELECT *, COUNT(*) FROM `table` GROUP BY (`otheridentifier`) ORDER BY `time` DESC LIMIT 3

将返回具有正确计数的5,3,1的id,但我想要5,4,2。

该帖子的解决方案是

SELECT * FROM 'table' WHERE 'id' = (SELECT 'id'
FROM 'table' as 'alt'
WHERE 'alt'.'otheridentifier' = 'table'.'otheridentifier'
ORDER BY 'time' DESC
LIMIT 1) ORDER BY 'time' DESC LIMIT 3

但是我没有看到如何获取计数,因为我需要在那里进行分组:如果我在其开头添加COUNT(*),我会得到ERROR 1140 (42000): Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause

1 个答案:

答案 0 :(得分:0)

SELECT *, COUNT(*)
FROM `table`
GROUP BY (`otheridentifier`)
ORDER BY COUNT(*) DESC LIMIT 3
^^^^^^^^^^^^^^^^^

只需更改order-by子句即可。在分组/聚合完成后完成排序,因此您可以按这些聚合函数的结果进行排序。