MySQL get row position in ORDER BY

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

With the following MySQL table:

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


        
9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 14:39

    Use this:

    SELECT x.id, 
           x.position,
           x.name
      FROM (SELECT t.id,
                   t.name,
                   @rownum := @rownum + 1 AS position
              FROM TABLE t
              JOIN (SELECT @rownum := 0) r
          ORDER BY t.name) x
     WHERE x.name = 'Beta'
    

    ...to get a unique position value. This:

    SELECT t.id,
           (SELECT COUNT(*)
              FROM TABLE x
             WHERE x.name <= t.name) AS position,
           t.name    
      FROM TABLE t      
     WHERE t.name = 'Beta'
    

    ...will give ties the same value. IE: If there are two values at second place, they'll both have a position of 2 when the first query will give a position of 2 to one of them, and 3 to the other...

提交回复
热议问题