Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4161082
  • 博文数量: 240
  • 博客积分: 11504
  • 博客等级: 上将
  • 技术积分: 4277
  • 用 户 组: 普通用户
  • 注册时间: 2006-12-28 14:24
文章分类

全部博文(240)

分类: Mysql/postgreSQL

2007-09-11 11:59:02

今天在坛子上看到了,顺便写下来。
有两种方法:
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)
阅读(11256) | 评论(4) | 转发(0) |
给主人留下些什么吧!~~

JoakMa2016-07-08 17:39:24

第一个的有个问题:如果有100个用户是相同的score,那么这个排名就不准确了! 这个如何解决?如果改为>=score,也会不准确~

JoakMa2016-07-08 17:39:24

第一个的有个问题:如果有100个用户是相同的score,那么这个排名就不准确了! 这个如何解决?如果改为>=score,也会不准确~

denghai3152010-09-11 11:41:18

不错啊

chinaunix网友2010-03-18 11:40:55

我一个学生有多次考试,我按每次的考试分组,排名查出来都是一样的