旗下导航:搜·么
当前位置:网站首页 > MySQL教程 > 正文

MySQL运用变量完成种种排序实例详解【MySQL教程】,MySQL,各种,实现

作者:搜教程发布时间:2019-11-27分类:MySQL教程浏览:21评论:0


导读:变量能够完成种种排序,本文重要引见了MySQL运用变量完成种种排序,须要的朋侪能够参考下,希望能协助到人人。中心代码--下面我演示下MySQL中的排序列的完成...
变量能够完成种种排序,本文重要引见了MySQL运用变量完成种种排序,须要的朋侪能够参考下,希望能协助到人人。

中心代码


--下面我演示下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 |
+------+------+-------+

人人学会了吗?赶忙着手尝试一下吧。

相干引荐:

js 种种排序要领和sort要领的区分详解

php中种种排序函数运用体式格局总结

关于种种排序的细致引见

以上就是MySQL运用变量完成种种排序实例详解的细致内容,更多请关注ki4网别的相干文章!

标签:MySQL各种实现


欢迎 发表评论: