MySQL使用变量实现各种排序
2019/6/30 18:18:53
本文主要是介绍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 | +------+------+-------+
这篇关于MySQL使用变量实现各种排序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-20部署MySQL集群入门:新手必读指南
- 2024-11-20部署MySQL集群教程:初学者指南
- 2024-11-20部署MySQL集群项目实战:新手教程
- 2024-11-20部署MySQL集群资料:新手入门教程
- 2024-11-20MySQL集群部署教程:入门级详解
- 2024-11-20MySQL集群教程:入门与实践指南
- 2024-11-20部署MySQL集群教程:新手入门指南
- 2024-11-20MySQL读写分离教程:轻松入门
- 2024-11-20部署MySQL集群入门:一步一步搭建你的数据库集群
- 2024-11-19部署MySQL集群学习:入门教程