把以逗号分隔的字符串转换成行
作者:互联网
业务表:
DROP table if EXISTS tbl_code;
CREATE TABLE tbl_code(
id int(11) not null auto_increment,
code varchar(100) not null,
PRIMARY KEY(id)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
insert into tbl_code values (1,'1,2,3,4,5');
insert into tbl_code values (2,'6,7,8,9');
序列表:
DROP table if EXISTS tbl_id;
CREATE TABLE tbl_id(
id int(11) not null,
PRIMARY KEY(id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into tbl_id values (0);
insert into tbl_id values (1);
insert into tbl_id values (2);
insert into tbl_id values (3);
insert into tbl_id values (4);
insert into tbl_id values (5);
insert into tbl_id values (6);
insert into tbl_id values (7);
insert into tbl_id values (8);
insert into tbl_id values (9);
insert into tbl_id values (10);
SELECT a.id,
SUBSTRING_INDEX(SUBSTRING_INDEX(a.code, ',', b.id+ 1), ',', -1) as code
from `tbl_id` a
left join `tbl_id` b on b.id<(LENGTH(a.`code`) - LENGTH( REPLACE(a.`code`, ',', ''))+ 1);
注意:tbl_id 序列表中的记录需要足够多,且必须从0开始,否则会转换不全。
标签:insert,code,分隔,into,逗号,values,tbl,id,成行 来源: https://www.cnblogs.com/donghuimao/p/14913170.html