如果项目已排序,是否可以运行select语句并获取行号?
我有一个这样的表:
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获取订单数量:
SELECT itemID, COUNT(*) as ordercount
FROM orders
GROUP BY itemID ORDER BY ordercount DESC;
这样,我就可以itemID
对表格中的每个表格进行计数:
+--------+------------+
| 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:=@rank+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)
ORDER BY rank ASC
(按升序顺序按等级排序)。我想这是您的意思,但顺序不正确