MYSQL获得行级别

时间:2012-01-11 01:34:46

标签: php mysql sql

我有一个mysql表,我需要获得随机行并获得总视图的等级

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

例如:

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

$rand可能是1或2等。

我需要通过totalview获得此行的排名

感谢的

2 个答案:

答案 0 :(得分:2)

SELECT *,
       (SELECT COUNT(*) FROM table t2 WHERE totalview > t1.totalview ) + 1 cnt
  FROM table t1
 WHERE id = '$rand'; 

答案 1 :(得分:0)

SELECT SUM(ref.totalview < t.totalview) FROM t1 CROSS JOIN t1 ref WHERE t1.id = '$rand'