ranking entries in mysql table

后端 未结 5 1297
清歌不尽
清歌不尽 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:04

    hobodave's solution is very good. Alternatively, you could add a separate rank column and then, whenever a row's popularity is UPDATEd, query to determine whether that popularity update changed its ranking relative to the row above and below it, then UPDATE the 3 rows affected. You'd have to profile to see which method is more efficient.

    0 讨论(0)
  • 2021-02-06 13:09

    If you're doing this using PDO then you need to modify the query to all be within the single statement in order to get it to work properly. See PHP/PDO/MySQL: Convert Multiple Queries Into Single Query

    So hobodave's answer becomes something like:

    SELECT t.*, (@count := @count + 1) as rank
    FROM table t 
    CROSS JOIN (SELECT @count := 0) CONST
    ORDER BY t.popularity;
    
    0 讨论(0)
  • 2021-02-06 13:16

    You are right that the second approach is inefficent, if the rank column is updated on every table read. However, depending on how many updates there are to the database, you could calculate the rank on every update, and store that - it is a form of caching. You are then turning a calculated field into a fixed value field.

    This video covers caching in mysql, and although it is rails specific, and is a slightly different form of caching, is a very similar caching strategy.

    0 讨论(0)
  • 2021-02-06 13:16

    If you are using an InnoDb table then you may consider building a clustered index on the popularity column. (only if the order by on popularity is a frequent query). The decision also depends on how varied the popularity column is (0 - 3 not so good).

    You can look at this info on clustered index to see if this works for your case: http://msdn.microsoft.com/en-us/library/ms190639.aspx

    This refers to SQL server but the concept is the same, also look up mysql documentation on this.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
提交回复
热议问题