ranking entries in mysql table

后端 未结 5 1358
清歌不尽
清歌不尽 2021-02-06 12:44

I have a MySQL table with many rows. The table has a popularity column. If I sort by popularity, I can get the rank of each item. Is it possible to retrieve the rank of a partic

5条回答
  •  轮回少年
    2021-02-06 13:18

    There is no way to calculate the order (what you call rank) of something without first sorting the table or storing the rank.

    If your table is properly indexed however (index on popularity) it is trivial for the database to sort this so you can get your rank. I'd suggest something like the following:

    Select all, including rank

    SET @rank := 0;
    SELECT t.*, @rank := @rank + 1
    FROM table t
    ORDER BY t.popularity;
    

    To fetch an item with a specific "id" then you can simply use a subquery as follows:

    Select one, including rank

    SET @rank := 0;
    SELECT * FROM (
      SELECT t.*, @rank := @rank + 1
      FROM table t
      ORDER BY t.popularity
    ) t2
    WHERE t2.id = 1;
    

提交回复
热议问题