( 轉 ) Mysql group_concat 的反向應用實現(Mysql列轉行)
阿新 • • 發佈:2018-06-11
IT 轉換成 sele art start enc star In str
用過Mysql的都知道她有一個很好的實現行轉列功能的函數group_concat函數,非常方便
點擊(此處)折疊或打開
- SELECT
- *
- FROM
- group_test;
- SELECT
- id,
- GROUP_CONCAT(sub_id)
- FROM
- `group_test`
- GROUP BY
- id;
現在的需求是有上面圖二類似的結果集,需要把列二拆分 轉換成行記錄
我們知道如果是單條記錄通過SUBSTRING_INDEX容易實現
點擊(此處)折疊或打開
- select id,SUBSTRING_INDEX(sub_id,‘,‘,1) from group_test where id=3
- UNION
- select id,SUBSTRING_INDEX(SUBSTRING_INDEX(sub_id,‘,‘,2),‘,‘,-1) from group_test where id=3
- UNION
- select id,SUBSTRING_INDEX(SUBSTRING_INDEX(sub_id,‘,‘,3),‘,‘,-1) from group_test where id=3
但是如果是N條呢?同樣也是可以使用SUBSTRING_INDEX來實現,只不過需要一個配置表,通過CROSS JOIN交叉連接實現,先看下CROSS JOIN
點擊(此處)折疊或打開
- SELECT
- *
- FROM
- (SELECT 1 UNION SELECT 2) t1
- CROSS JOIN (SELECT 3 UNION SELECT 4) t2
下面就通過CROSS JOIN和SUBSTRING_INDEX實現我們的需求,首先構建一個配置表
點擊(此處)折疊或打開
- CREATE TABLE digits (digit INT(1));
- INSERT INTO digits
- VALUES
- (0),
- (1),
- (2),
- (3),
- (4),
- (5),
- (6),
- (7),
- (8),
- (9);
- CREATE TABLE sequence (seq INT(3));
- INSERT INTO sequence (
- SELECT
- D1.digit + D2.digit * 10
- FROM
- digits D1
- CROSS JOIN digits D2
- );
然後
點擊(此處)折疊或打開
- SELECT
- id,
- SUBSTRING_INDEX(
- SUBSTRING_INDEX(sub_id, ‘,‘, seq),
- ‘,‘ ,- 1
- ) sub_id,
- seq
- FROM
- sequence
- CROSS JOIN group_test
- WHERE
- seq BETWEEN 1
- AND (
- SELECT
- 1 + LENGTH(sub_id) - LENGTH(REPLACE(sub_id, ‘,‘, ‘‘))
- )
- ORDER BY
- id,
- sub_id;
原貼: http://blog.chinaunix.net/uid-411974-id-3990697.html
( 轉 ) Mysql group_concat 的反向應用實現(Mysql列轉行)