MySQL - Get row number on select

后端 未结 5 2267
轻奢々
轻奢々 2020-11-22 00:43

Can I run a select statement and get the row number if the items are sorted?

I have a table like this:

mysql> describe orders;
+-------------+----         


        
5条回答
  •  野性不改
    2020-11-22 01:09

    Swamibebop's solution works, but by taking advantage of table.* syntax, we can avoid repeating the column names of the inner select and get a simpler/shorter result:

    SELECT @r := @r+1 , 
           z.* 
    FROM(/* your original select statement goes in here */)z, 
    (SELECT @r:=0)y;
    

    So that will give you:

    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;
    

提交回复
热议问题