打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
MYSQL成绩排名
今天在坛子上看到了,顺便写下来。
有两种方法:
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)
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
MySQL 快速创建千万级测试数据
查询分组后每个分组的前几条记录
mysql中如何改变字段或者列的顺序
CSDN热榜排名追踪工具上线,随时查看热榜链路数据
PHP 备份数据库代码(生成word,excel,json,xml,sql)
如何查看MySQL数据库的死锁日志
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服