mysql 成績排名

來源:互聯網
上載者:User
今天在罈子上看到了,順便寫下來。 
有兩種方法: 
1、效率不高,因為有子查詢。但是簡潔。而且我對SOCRES表做了INDEX。所以效能上也差不了多少。 
mysql> show create table scores\G
*************************** 1. row ***************************
       Table: scores
Create Table: CREATE TABLE `scores` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `score` int(11) DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `k_s` (`score`)
) ENGINE=MyISAM AUTO_INCREMENT=1000001 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC 
1 row in set (0.00 sec)

  
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 ; 
  
mysql> call sp_rank(100);
+-----+-------+--------+
| id  | score | rank   |
+-----+-------+--------+
| 100 |    64 | 370311 |
+-----+-------+--------+
1 row in set (1.02 sec) 
Query OK, 0 rows affected (1.02 sec)
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.