mysql分组排序加序号(不用存储过程,就简简单单sql语句哦)

做前端好长时间了,好久没动sql了。在追一个喜欢的女孩,做测试的,有这么个需求求助与本屌丝,机会难得,开始折腾起来,配置mysql,建库,建表....

一 建表

CREATE TABLE `my_test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `parent_code` varchar(255) DEFAULT NULL,
  `code` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

二 模拟数据

INSERT INTO `my_test` (  `parent_code`, `code`) VALUES ('01', '001');
INSERT INTO `my_test` (  `parent_code`, `code`) VALUES ('01', '002');
INSERT INTO `my_test` (  `parent_code`, `code`) VALUES ('02', '001');
INSERT INTO `my_test` (  `parent_code`, `code`) VALUES ('01', '003');
INSERT INTO `my_test` (  `parent_code`, `code`) VALUES ('02', '002');
INSERT INTO `my_test` (  `parent_code`, `code`) VALUES ('03', '001');
INSERT INTO `my_test` (  `parent_code`, `code`) VALUES ('04', '001');

查询 结果如下:

三 不分组加序号

select  (@i := @i + 1) rownum,my_test.*  from    my_test , (SELECT  @i := 0) AS a  group  by   parent_code ,code ,id  order  by   parent_code 

结果如下:

解释一下 这个地方用了@i变量  刚开始的 让 @i=0   然后 每查询一条 让  @i+=1

四  分组 排序 加 序号了

刚开始的没 思路,就度娘了 ,有用 存储过程  创建临时表  插入临时表实现的,还有用存储过程游标实现,对于好久没动sql,而且之前也没写过mysql 查询的 淫来说 好复杂,

好囧 ,赶脚要再我女神面前丢人了,but 多谢上天眷顾,查看我女神聊天记录的时候,灵感来了,为什么不继续发掘下变量的作用呢 。

于是 再定义一个变量@pre_parent_code:='' 再存上一个 parent_code  ,只要  pre_parent_code不等于当前的parent_code  让 @i:=0 else  @i+=1 就ok了

select 
                        -- rownum  判断  @pre_parent_code是否和当前的parent_code一样 ,true:让 @i+=1 false:重置@i
                    
                        (@i := case  when  @pre_parent_code=parent_code then @i + 1 else 1 end )  rownum,  
                        
                        my_test.*,
                        --  设置 @pre_parent_code等于上一个 parent_code 
                         (@pre_parent_code:=parent_code)  
                         
                     from    my_test , 
                     
                     (SELECT  @i := 0, @pre_parent_code:='') AS a  
                     
                     group  by   parent_code ,code ,id  
                     
                     order  by   parent_code 

结果如下图

遇到难题千万别放弃,万一实现了呢,更何况这是 爱情的力量呢  ,哇O(∩_∩)O哈哈哈~

 

转载于:https://www.cnblogs.com/CharlieLau/p/6737243.html

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值