Home  >  Article  >  Database  >  Detailed explanation of MySQL using variables to implement various sorting examples

Detailed explanation of MySQL using variables to implement various sorting examples

小云云
小云云Original
2018-01-24 13:45:37999browse

Variables can achieve various sortings. This article mainly introduces the use of variables by MySQL to achieve various sortings. Friends who need it can refer to it. I hope it can help everyone.

Core code


--下面我演示下MySQL中的排序列的实现
--测试数据
CREATE TABLE tb
(
score INT
);
INSERT tb SELECT 
5 UNION ALL SELECT 
4 UNION ALL SELECT 
4 UNION ALL SELECT 
4 UNION ALL SELECT 
3 UNION ALL SELECT 
2 UNION ALL SELECT
1;
--1.row_number式的排序
SET @row_number =0;
SELECT @row_number := @row_number+1 AS row_number,score 
FROM tb 
ORDER BY score DESC ;
+------------+-------+
| row_number | score |
+------------+-------+
|     1 |   5 |
|     2 |   4 |
|     3 |   4 |
|     4 |   4 |
|     5 |   3 |
|     6 |   2 |
|     7 |   1 |
+------------+-------+
--2.dense_rank式的排序
SET @dense_rank = 0,@prev_score = NULL;
SELECT @dense_rank :=IF(@prev_score=score,@dense_rank,@dense_rank+1) AS decnse_rank,
  @prev_score := score AS score 
FROM tb 
ORDER BY score DESC ; 
+-------------+-------+
| decnse_rank | score |
+-------------+-------+
|      1 |   5 |
|      2 |   4 |
|      2 |   4 |
|      2 |   4 |
|      3 |   3 |
|      4 |   2 |
|      5 |   1 |
+-------------+-------+
--3.rank式的排序
SET @row=0,@rank=0,@prev_score=NULL;
SELECT @row:=@row+1 AS ROW,
    @rank:=IF(@prev_score=score,@rank,@row) AS rank,
    @prev_score:=score AS score
FROM tb 
ORDER BY score DESC;
+------+------+-------+
| ROW | rank | score |
+------+------+-------+
|  1 |  1 |   5 |
|  2 |  2 |   4 |
|  3 |  2 |   4 |
|  4 |  2 |   4 |
|  5 |  5 |   3 |
|  6 |  6 |   2 |
|  7 |  7 |   1 |
+------+------+-------+

Have you learned it? Hurry up and try it out.

Related recommendations:

js Detailed explanation of the differences between various sorting methods and sort methods

#Summary of how to use various sorting functions in php

Detailed introduction to various sorting

The above is the detailed content of Detailed explanation of MySQL using variables to implement various sorting examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn