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

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

一 建表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;

二 模拟数据sql

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');

查询 结果以下:测试

三 不分组加序号spa

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 

结果以下:3d

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

四  分组 排序 加 序号了blog

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

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

因而 再定义一个变量@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哈哈哈~