做前端好長時間了,好久沒動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哈哈哈~