zoukankan      html  css  js  c++  java
  • 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哈哈哈~

  • 相关阅读:
    5分钟机器学习
    快速排序
    数据预处理 总结
    正则化 / 特征选择
    424. 替换后的最长重复字符 sliding window中的注意点
    自然语言处理算法精讲P3
    76. 最小覆盖子串
    3.无重复字符的最长子串 —— sliding window
    自然语言处理算法精讲 P1
    18.四数之和
  • 原文地址:https://www.cnblogs.com/CharlieLau/p/6737243.html
Copyright © 2011-2022 走看看