如果项目已排序,是否可以运行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
+--------+------------+ | itemID | ordercount | +--------+------------+ | 388 | 3 | | 234 | 2 | | 3432 | 1 | | 693 | 1 | | 3459 | 1 | +--------+------------+
我也想获得行号,所以我可以知道那itemID=388是第一行,234第二行,等等(本质上是订单的排名,而不仅仅是原始计数)。我知道当我返回结果集时可以在Java中执行此操作,但是我想知道是否有一种方法可以纯粹在SQL中处理它。
itemID=388
234
更新资料
设置等级会将其添加到结果集中,但顺序不正确:
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)
看看这个。
将查询更改为:
SET @rank=0; SELECT @rank:=@rank+1 AS rank, itemID, COUNT(*) as ordercount FROM orders GROUP BY itemID ORDER BY ordercount DESC; SELECT @rank;
最后选择是您的数量。