MySQL get row position in ORDER BY

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

With the following MySQL table:

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


        
9条回答
  •  佛祖请我去吃肉
    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.

提交回复
热议问题