mysql把以逗号连接的字段拆分成列表
作者:mmseoamin日期:2024-01-30

需求:

由目标表testtt

mysql把以逗号连接的字段拆分成列表,第1张

得到分隔后的数据

mysql把以逗号连接的字段拆分成列表,第2张

步骤一:

创建中间表test

CREATE TABLE `test` (

  `id` int(11) NOT NULL,

  `name` varchar(255) DEFAULT NULL,

  PRIMARY KEY (`id`) USING BTREE

) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC

添加数据

insert into `test` (`id`, `name`) values('0',NULL);

insert into `test` (`id`, `name`) values('1',NULL);

insert into `test` (`id`, `name`) values('2',NULL);

insert into `test` (`id`, `name`) values('3',NULL);

insert into `test` (`id`, `name`) values('4',NULL);

insert into `test` (`id`, `name`) values('5',NULL);

insert into `test` (`id`, `name`) values('6',NULL);

insert into `test` (`id`, `name`) values('7',NULL);

insert into `test` (`id`, `name`) values('8',NULL);

insert into `test` (`id`, `name`) values('9',NULL);

insert into `test` (`id`, `name`) values('10',NULL);

insert into `test` (`id`, `name`) values('11',NULL);

insert into `test` (`id`, `name`) values('12',NULL);

 步骤二:

创建目标表testtt

CREATE TABLE `testtt` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `value` varchar(255) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

添加数据

insert into `testtt` (`id`, `value`) values('1','1,2,3');

insert into `testtt` (`id`, `value`) values('2','4,5');

insert into `testtt` (`id`, `value`) values('3','6');

insert into `testtt` (`id`, `value`) values('4','7,8');

步骤三:

编写sql

SELECT     
	a.id, 
	SUBSTRING_INDEX( SUBSTRING_INDEX( a.value, ',', b.id + 1 ), ',', -1 ) AS VALUE 
FROM 	testtt a
JOIN 	test b ON b.id < ( LENGTH( a.value ) - LENGTH( REPLACE ( a.value, ',', '' ))+ 1 )

sql注意点:

1,test表的行数要大于需要拆分字段拆分后的数量(这里是单条数据拆分后的数量),否者会少数据

2,test表id需要从0连续的,否则也会少数据