MySQL使用变量实现各种排序

时间:2022-08-27 09:29:13

核心代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
--下面我演示下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 |
+------+------+-------+

原文链接:http://blog.csdn.net/feixianxxx/article/details/5807973