mysql根据逗号将一行数据拆分成多行数据

1、原始数据演示

mysql根据逗号将一行数据拆分成多行数据_第1张图片

处理结果演示

mysql根据逗号将一行数据拆分成多行数据_第2张图片

sql语句

SELECT
	a.id,
	a. NAME,
	substring_index(
		substring_index(
			a.shareholder,
			',',
			b.help_topic_id + 1
		),
		',' ,- 1
	) AS shareholder
FROM
	company a
JOIN mysql.help_topic b ON b.help_topic_id < (
	length(a.shareholder) - length(
		REPLACE (a.shareholder, ',', '')
	) + 1
)

建表语句

CREATE TABLE `company` (
  `id` int(20) DEFAULT NULL,
  `name` varchar(100) DEFAULT NULL,
  `shareholder` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `company` VALUES ('1', '阿里巴巴', '马云');
INSERT INTO `company` VALUES ('2', '淘宝', '马云,孙正义');

原理分析

这个join最基本原理是笛卡尔积。通过这个方式来实现循环。

分析:

length(a.path) - length(replace(a.path,‘,’,‘’))+1 表示了,按照逗号分割后,分割需要循环的次数。

join过程:

根据ID进行循环

{

判断:i 是否 <= n

获取最靠近第 i 个逗号之前的数据, 即 substring_index(substring_index(a.path,‘,’,b.help_topic_id),‘,’,-1)

}

这种方法的缺点在于,我们需要一个拥有连续数列的独立表。并且连续数列的最大值一定要大于符合分割的值的个数。

例如有一行的path有100个逗号分割的值,那么我们的table 就需要有至少100个连续行。

当然,mysql内部也有现成的连续数列表可用。如mysql.help_topic: help_topic_id 共有504个数值,一般能满足于大部分需求了。

你可能感兴趣的:(数据库,mysql)