MySQL get row position in ORDER BY

前端 未结 9 1065
囚心锁ツ
囚心锁ツ 2020-11-22 13:57

With the following MySQL table:

+-----------------------------+
+ id INT UNSIGNED             +
+ name VARCHAR(100)           +
+----------------------------         


        
相关标签:
9条回答
  • 2020-11-22 14:45

    I was going through the accepted answer and it seemed bit complicated so here is the simplified version of it.

    SELECT t,COUNT(*) AS position FROM t      
     WHERE name <= 'search string' ORDER BY name
    
    0 讨论(0)
  • 2020-11-22 14:52

    If the query is simple and the size of returned result set is potentially large, then you may try to split it into two queries.

    The first query with a narrow-down filtering criteria just to retrieve data of that row, and the second query uses COUNT with WHERE clause to calculate the position.

    For example in your case

    Query 1:

    SELECT * FROM tbl WHERE name = 'Beta'

    Query 2:

    SELECT COUNT(1) FROM tbl WHERE name >= 'Beta'

    We use this approach in a table with 2M record and this is way more scalable than OMG Ponies's approach.

    0 讨论(0)
  • 2020-11-22 14:53

    I have similar types of problem where I require rank(Index) of table order by votes desc. The following works fine with for me.

    Select *, ROW_NUMBER() OVER(ORDER BY votes DESC) as "rank"
    From "category_model"
    where ("model_type" = ? and "category_id" = ?)
    
    0 讨论(0)
提交回复
热议问题