sofh7777 发表于 2017-12-13 11:32:57

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 agroupby   parent_code ,code ,idorderby   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  
                  
  (
@i := casewhen@pre_parent_code=parent_code then @i + 1 else 1 end )rownum,  my_test.
*,  (@pre_parent_code:=parent_code)
  from    my_test ,
  (SELECT@i := 0, @pre_parent_code:='') AS a
  groupby   parent_code ,code ,id
  orderby   parent_code
  

  结果如下图

  遇到难题千万别放弃,万一实现了呢,更何况这是 爱情的力量呢,哇O(∩_∩)O哈哈哈~
页: [1]
查看完整版本: mysql分组排序加序号(不用存储过程,就简简单单sql语句哦)