分数排名 mysql_mysql的分数排名处理

本文探讨了两种在MySQL中获取Score表排名前10的数据的方法。第一种方法使用子查询,虽然简洁但效率较低;第二种方法通过存储过程实现,提高了效率。此外,还提到了在PHP端处理查询结果来获取排名的方案。
摘要由CSDN通过智能技术生成

问题:将数据库Score表排名 返回排名前10的

DB有两种方法:

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)

还有另外一种方法 PHP端处理:

while($row = mysql_fetch_array($result))     {                                $idx++;                 //超过10的场合         if($idx>10)         {             $scorenow=$row['c_score'];                         if($scorenow==$scoreago)             {                                 $scoreago=$scorenow;                 $arrscore[$idx]=array("index"=>$idx,"idx"=>$idx2,"name"=>$row['c_name'],"score"=>$row['c_score'],"location"=>$row['c_location']);             }             else             {                 break;             }         }         else         {                                       $scorenow=$row['c_score'];                               if($scorenow!=$scoreago)                {                    $idx2++;                }                $scoreago=$scorenow;                                       $arrscore[$idx]=array("index"=>$idx,"idx"=>$idx2,"name"=>$row['c_name'],"score"=>$row['c_score'],"location"=>$row['c_location']);                //echo $arrscore[$idx];         }     }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值