MySQL 5.7.16 字符串拆分 -> 单列变多行记录

时间:2023-02-07 10:27:30



字符串拆分,单列变成多行,并保留原来的其它字段的数据,准备测试数据:

mysql> create table t1(c1 varchar(32),c2 varchar(32));Query OK, 0 rows affected (0.02 sec)

mysql> INSERT INTO t1 SELECT 'man' c1,'123,234,567,789' c2 UNION ALL SELECT 'guo','-12,-87,-09,132' UNION ALL SELECT 'fang','1024,2387,1209,1032';
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> select * from t1;
+------+---------------------+
| c1 | c2 |
+------+---------------------+
| man | 123,234,567,789 |
| guo | -12,-87,-09,132 |
| fang | 1024,2387,1209,1032 |
+------+---------------------+
3 rows in set (0.00 sec)

mysql>


需要达到的效果是,左边变成右边,按照逗号拆分出来,单列变成多行记录,而且保留原来的其它列数据,如下图所示:

MySQL 5.7.16 字符串拆分 -> 单列变多行记录


 #,blog原地址:http://blog.csdn.net/mchdba/article/details/53889803,作者mchdba,谢绝转载


这个复杂的实现,单条的sql或者几条sql无法达到,需要临时表存储中间数据,所以编写存储过程,间接实现,存储过程如下:

DELIMITER $$USE `test`$$DROP PROCEDURE IF EXISTS `proc_cur_split_str`$$USE `test`$$CREATE PROCEDURE test.proc_cur_split_str()BEGIN    DECLARE v_c1 VARCHAR(20);    DECLARE v_c2 VARCHAR(60);    DECLARE _done INT DEFAULT 0;         DECLARE cur_strs CURSOR FOR SELECT c1,c2 from test.t1 ;    DECLARE CONTINUE HANDLER FOR NOT FOUND BEGIN SET _done=1; END;     DROP TABLE IF EXISTS test.ZZ_2;        CREATE TABLE test.ZZ_2(C1 VARCHAR(20),CN VARCHAR(60));    OPEN cur_strs;        FETCH cur_strs INTO v_c1, v_c2;        WHILE _done != 1  DO 			DROP TABLE IF EXISTS test.ZZ_1;			CREATE TABLE ZZ_1(CN VARCHAR(60)); 			SET @b=v_c2;			 SET @a = CONCAT(CONCAT("insert into test.ZZ_1 values('",REPLACE(@b,',',"'),('")),"')");			-- SELECT @a;			 PREPARE stmt1 FROM @a;  			EXECUTE stmt1;  			-- SELECT v_c1,t.* FROM test.ZZ_1 t;			INSERT INTO ZZ_2 SELECT v_c1,t.* FROM test.ZZ_1 t;						COMMIT;   			-- SELECT * FROM test.ZZ_2;            FETCH cur_strs INTO v_c1, v_c2;	END WHILE;    CLOSE cur_strs;          SELECT * FROM test.ZZ_2;  END;      


执行存储过程,得到执行结果,符合心理预期,单列C1变成多行,并且保留了原来的其它字段c1的数据值,如下所示,

MySQL 5.7.16 字符串拆分 -> 单列变多行记录