Let your detours in MySQL rank (), row_number (), dense_rank () to sort

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )
create table students(
	id int(4)  auto_increment primary key,
	name varchar(50) not null, 
	score int(4) not null
	);

First create a simple table with test data into a table.

insert into students(name,score) values('curry', 100),
	('klay', 99),
	('KD', 100), 
	('green', 90), 
	('James', 99), 
	('AD', 96);

Look at the data inserted:

select * from students;

 

I started using three different methods to sort:

select id, name, rank() over(order by score desc) as r from students;
select id, name, DENSE_RANK() OVER(order by score desc) as dense_r from students;
select id, name, row_number() OVER(order by score desc) as row_r from students;

Of course, you can write the same table:

select id, name, rank() over(order by score desc) as r,
	DENSE_RANK() OVER(order by score desc) as dense_r,
	row_number() OVER(order by score desc) as row_r
from students;

One thing to note is the alias after as, and do not duplicate names in front of the function name, otherwise it will error.

The result is very clear, concrete will not explain, I believe we see the results very clearly the difference between three kinds of sort.

 

 

 

 

Guess you like

Origin blog.csdn.net/sqsltr/article/details/94408487