mysql 顯示行號,以及分組排序


建表:

CREATE TABLE `my_tb` (
  `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_tb` (  `parent_code`, `code`) VALUES ('01', '001');
INSERT INTO `my_tb` (  `parent_code`, `code`) VALUES ('01', '002');
INSERT INTO `my_tb` (  `parent_code`, `code`) VALUES ('02', '001');
INSERT INTO `my_tb` (  `parent_code`, `code`) VALUES ('01', '003');
INSERT INTO `my_tb` (  `parent_code`, `code`) VALUES ('02', '002');
INSERT INTO `my_tb` (  `parent_code`, `code`) VALUES ('03', '001');
INSERT INTO `my_tb` (  `parent_code`, `code`) VALUES ('04', '001');

 

     

查詢行號:

   

-- 生成 行號
select @r:=@r+1 as row_num , a.* from  my_tb a ,(select @r:=0) b

顯示分組號:

-- 生成 分組排序號

select  
     @group_row:=CASE when @parent_code=a.parent_code then  @group_row+1 else 1 end as groupRow,
     @parent_code:=a.parent_code as parent_code,
     a.code  

  from  my_tb a ,( select @group_row:=1, @parent_code:='') as b
 ORDER BY   a.parent_code , a.code 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM