MySQL-获取选择的行号如果对项进行排序,我可以运行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 ordercountFROM ordersGROUP 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)
3 回答
翻过高山走不出你
TA贡献1875条经验 获得超3个赞
SELECT @rn:=@rn+1 AS rank, itemID, ordercountFROM ( SELECT itemID, COUNT(*) AS ordercount FROM orders GROUP BY itemID ORDER BY ordercount DESC) t1, (SELECT @rn:=0) t2;
不负相思意
TA贡献1777条经验 获得超10个赞
table.*
select
SELECT @r := @r+1 , z.* FROM(/* your original select statement goes in here */)z, (SELECT @r:=0)y;
SELECT @r := @r+1 , z.* FROM( SELECT itemID, count(*) AS ordercount FROM orders GROUP BY itemID ORDER BY ordercount DESC )z, (SELECT @r:=0)y;
添加回答
举报
0/150
提交
取消