MySQL 8.0版本 自動排序函數dense_rank() over()、rank() over()、row_num() over()用法和區別


  三個函數均MySQL 8.x 以上版本,8.x以下版本會報語法錯誤,屬於正常現象。

  MySQL 8.x 實際上就是 MySQL 5.8x,大概是為了通過更大版本型號數字,證明自己比友商先進吧。

  MYSql版本下載:https://downloads.mysql.com/archives/installer/

區別:

  • rank():是並列排序,會跳過重復序號
  • dense_rank():是並列排序,不會跳過重復序號
  • row_number():是順序排序,不跳過任何一個序號,就是行號

用法:

數據准備:

create table students(
    id int(11)  auto_increment primary key,
    name varchar(50) not null, 
    score int(4) not null
    );
 
insert into students(name,score) values
('zhangsan', 100),
('lisi', 99),
('wangwu', 100), 
('trx', 90), 
('pjf', 99), 
('wzm', 96);

查看下插入的數據:

select * from students;

使用三種不同的方法進行排序:

select 
    id, 
    name, 
    rank() over(order by score desc) `rank`,
    row_number() over(order by score desc) `row_number`,
    dense_rank() over(order by score desc) `dense_rank`
from students;
 
--------------------------------- 結果 ------------------------------------
+----+----------+-------+------+------------+------------+
| id | name     | score | rank | row_number | dense_rank |
+----+----------+-------+------+------------+------------+
|  1 | zhangsan |   100 |    1 |          1 |          1 |
|  3 | wangwu   |   100 |    1 |          2 |          1 |
|  2 | lisi     |    99 |    3 |          3 |          2 |
|  5 | pjf      |    99 |    3 |          4 |          2 |
|  6 | wzm      |    96 |    5 |          5 |          3 |
|  4 | trx      |    90 |    6 |          6 |          4 |

 

轉載:https://blog.csdn.net/weixin_43161811/article/details/112001469


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM