博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
MYSQL成绩排名
阅读量:6954 次
发布时间:2019-06-27

本文共 1586 字,大约阅读时间需要 5 分钟。

hot3.png

今天在坛子上看到了,顺便写下来。
有两种方法:
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)

本文出自 “” 博客,转载请与作者联系!

转载于:https://my.oschina.net/u/585111/blog/219513

你可能感兴趣的文章
ubuntu下mysql无法启动Couldn't find MySQL server (/usr/bin/mysqld_safe)”
查看>>
sleep函数——Gevent源码分析
查看>>
学习周总结
查看>>
通用窗口类 Inventory Pro 2.1.2 Demo1(下)
查看>>
第零次作业
查看>>
在阿里云服务器windows server2012r iis上部署.net网站
查看>>
为easyui添加多条件验证
查看>>
Linux mem/swap/buffers/cached 区别
查看>>
13 memcache服务检查
查看>>
go install之后没有生成bin目录的原因(环境变量GOBIN)
查看>>
uva 10441(poj 2337 欧拉通路)
查看>>
DS博客作业07--查找
查看>>
Codeforces_733C
查看>>
[改善Java代码]动态加载不适合数组
查看>>
Mysql打开日志信息
查看>>
javaScript----Http对象封装
查看>>
Struts2入门
查看>>
纯JS,AJAX
查看>>
数据结构上机1顺序表
查看>>
如何搭建自己的SPRING INITIALIZR server
查看>>