SQL Group By 和 Order By
我有一个标签表,想从列表中获取计数最高的标签。
示例数据看起来像这样,
id (1) tag ('night')
id (2) tag ('awesome')
id (3) tag ('night')
使用
SELECT COUNT(*), `Tag` from `images-tags`
GROUP BY `Tag`
可以让我完美地返回我正在寻找的数据。 但是,我想对其进行组织,以便将最高标签计数排在前面,并将其限制为仅向我发送前 20 个左右。
我尝试了这个......
SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY COUNT(id) DESC
LIMIT 20
但我不断收到“无效使用组功能 - ErrNr 1111”
我做错了什么?
我正在使用 MySQL 4.1.25-Debian
I have a table of tags and want to get the highest count tags from the list.
Sample data looks like this
id (1) tag ('night')
id (2) tag ('awesome')
id (3) tag ('night')
using
SELECT COUNT(*), `Tag` from `images-tags`
GROUP BY `Tag`
gets me back the data I'm looking for perfectly. However, I would like to organize it, so that the highest tag counts are first, and limit it to only send me the first 20 or so.
I tried this...
SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY COUNT(id) DESC
LIMIT 20
and I keep getting an "Invalid use of group function - ErrNr 1111"
What am I doing wrong?
I'm using MySQL 4.1.25-Debian
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在所有版本的 MySQL 中,只需为 SELECT 列表中的聚合添加别名,然后按别名排序:
In all versions of MySQL, simply alias the aggregate in the SELECT list, and order by the alias:
尝试这个查询
Try this query
在 Oracle 中,类似的东西可以很好地将计数和排序分开。 我不确定它是否适用于 MySql 4。
In Oracle, something like this works nicely to separate your counting and ordering a little better. I'm not sure if it will work in MySql 4.
我不了解 MySQL,但在 MS SQL 中,您可以在
order by
子句中使用列索引。 我之前在使用group by
进行计数时已经这样做过,因为它往往更容易使用。就这样
变成了
I don't know about MySQL, but in MS SQL, you can use the column index in the
order by
clause. I've done this before when doing counts withgroup by
s as it tends to be easier to work with.So
Becomes
MySQL 5 版之前不允许在 ORDER BY 子句中使用聚合函数。
您可以使用已弃用的语法来绕过此限制:
1,因为它是您要分组的第一列。
MySQL prior to version 5 did not allow aggregate functions in ORDER BY clauses.
You can get around this limit with the deprecated syntax:
1, since it's the first column you want to group on.