mysql的分數排名處理

2021-05-22 21:19:05 字數 2180 閱讀 5767

問題:將資料庫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))

else

} else

$scoreago=$scorenow;

$arrscore[$idx]=array("index"=>$idx,"idx"=>$idx2,"name"=>$row['c_name'],"score"=>$row['c_score'],"location"=>$row['c_location']);

//echo $arrscore[$idx]; }

}

mysql 分數排名

表table1 欄位1 chengji 成績 欄位2 paiming 排名 50 0 80 0 70 0 20 0 90 0 如何用1條mysql查詢語句,執行後讓他們變成 欄位1 chengji 成績 欄位2 paiming 排名 50 4 80 2 70 3 20 5 90 1 solution...

MySql 分數排名

題目 編寫乙個 sql 查詢來實現分數排名。如果兩個分數相同,則兩個分數排名 rank 相同。請注意,平分後的下乙個名次應該是下乙個連續的整數值。換句話說,名次之間不應該有 間隔 id score 1 3.50 2 3.65 3 4.00 4 3.85 5 4.00 6 3.65 例如,根據上述給定...

MYSQL分數排名

編寫乙個 sql 查詢來實現分數排名。如果兩個分數相同,則兩個分數排名 rank 相同。請注意,平分後的下乙個名次應該是下乙個連續的整數值。換句話說,名次之間不應該有 間隔 id score 1 3.50 2 3.65 3 4.00 4 3.85 5 4.00 6 3.65 例如,根據上述給定的 s...