mysql> select count(1) from scores;
+----------+
| count(1) |
+----------+
| 1000000 |
+----------+
1 row in set (0.00 sec)
mysql> select id,score,(select count(1) from scores where score>= (select score
from scores where id = 100 order by score desc limit 1)) as rank from scores whe
re id = 100;
+-----+-------+--------+
| id | score | rank |
+-----+-------+--------+
| 100 | 64 | 370311 |
+-----+-------+--------+
1 row in set (1.05 sec)
2、分句完成。效率高。
預存程序:
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`sp_rank`$$
CREATE PROCEDURE `test`.`sp_rank`(IN str_id int(11))
BEGIN
-- user's score
DECLARE str_score int;
-- user's rank
DECLARE rank int;
select score from scores where id = str_id order by score desc limit 1 into str_score ;
select count(*) from scores where score >=str_score into rank;
-- output
select id,score,rank from scores where id = str_id;
END$$
DELIMITER ;