MySQL - Get row number on select

后端 未结 5 2132
轻奢々
轻奢々 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 00:52

    Take a look at this.

    Change your query to:

    SET @rank=0;
    SELECT @rank:=@rank+1 AS rank, itemID, COUNT(*) as ordercount
      FROM orders
      GROUP BY itemID
      ORDER BY ordercount DESC;
    SELECT @rank;
    

    The last select is your count.

    0 讨论(0)
  • 2020-11-22 00:55

    It's now builtin in MySQL 8.0 and MariaDB 10.2:

    SELECT
      itemID, COUNT(*) as ordercount,
      ROW_NUMBER OVER (PARTITION BY itemID ORDER BY rank DESC) as rank
    FROM orders
    GROUP BY itemID ORDER BY rank DESC
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-11-22 01:12
    SELECT @rn:=@rn+1 AS rank, itemID, ordercount
    FROM (
      SELECT itemID, COUNT(*) AS ordercount
      FROM orders
      GROUP BY itemID
      ORDER BY ordercount DESC
    ) t1, (SELECT @rn:=0) t2;
    
    0 讨论(0)
  • 2020-11-22 01:13

    You can use MySQL variables to do it. Something like this should work (though, it consists of two queries).

    SELECT 0 INTO @x;
    
    SELECT itemID, 
           COUNT(*) AS ordercount, 
           (@x:=@x+1) AS rownumber 
    FROM orders 
    GROUP BY itemID 
    ORDER BY ordercount DESC; 
    
    0 讨论(0)
提交回复
热议问题