简体   繁体   中英

MYSQL get row rank

I have a mysql table and I need to get random row and get the rank of total view

+--------+------------+---------+
| id     | name       |totalview|
+--------+------------+---------+
| 1      | ex1        |   20    |
| 2      | ex2        |   100   |
| 3      | ex3        |   30    |
| 4      | ex4        |   40    |
+--------+------------+---------+

for example :

SELECT * FROM `table` WHERE `id` = '$rand';

$rand may be 1 or 2 etc ..

I need to get rank of this row by totalview

thank's

SELECT *,
       (SELECT COUNT(*) FROM table t2 WHERE totalview > t1.totalview ) + 1 cnt
  FROM table t1
 WHERE id = '$rand'; 
SELECT SUM(ref.totalview < t.totalview) FROM t1 CROSS JOIN t1 ref WHERE t1.id = '$rand'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM