如果项目已排序,我可以运行select语句并获取行号吗?MySQL - 获取行号
我有这样的一个表:
SELECT itemID, COUNT(*) as ordercount
FROM orders
GROUP BY itemID ORDER BY ordercount DESC;
这让我在每个itemID
的计数:
mysql> describe orders;
+-------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------------+------+-----+---------+----------------+
| orderID | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| itemID | bigint(20) unsigned | NO | | NULL | |
+-------------+---------------------+------+-----+---------+----------------+
然后我就可以运行此查询通过ID来获得的订单数这样的表:
+--------+------------+
| itemID | ordercount |
+--------+------------+
| 388 | 3 |
| 234 | 2 |
| 3432 | 1 |
| 693 | 1 |
| 3459 | 1 |
+--------+------------+
我想要得到行号,所以我可以告诉itemID=388
是第一行,234
是第二等,(基本上是订单的排名,而不仅仅是一个原始计数)。我知道当我得到结果集时,我可以用Java来做到这一点,但我想知道是否有办法纯粹用SQL来处理它。
更新
设置排名将其添加到结果集,但不能正常下令:
mysql> SET @rank=0;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @rank:[email protected]+1 AS rank, itemID, COUNT(*) as ordercount
-> FROM orders
-> GROUP BY itemID ORDER BY rank DESC;
+------+--------+------------+
| rank | itemID | ordercount |
+------+--------+------------+
| 5 | 3459 | 1 |
| 4 | 234 | 2 |
| 3 | 693 | 1 |
| 2 | 3432 | 1 |
| 1 | 388 | 3 |
+------+--------+------------+
5 rows in set (0.00 sec)
为了将来的参考:如果你想从秩1到秩5排序,使用'ORDER BY秩ASC'(按ASCending顺序排列)。我想这就是你的意思*,但没有正确的命令* – GroundZero 2015-01-09 12:57:23
[ROW \ _NUMBER()在MySQL中可能的重复](http://stackoverflow.com/questions/1895110/row-number-in-mysql) – 2016-05-25 14:13:48