项目需求要将数据某个字段以逗号分割成多条数据,就是1 -> N,其他字段数据一致,这里以项目中实际需求为例。
表中brand_name
是以逗号链接的多个品牌名,例如(BELLE,思加图,他她,百思图,Bata),要将该字段变成五条数据,其中brand_name
变成如下所示,这里采用substring_index
函数和JOIN
关联实现,这里需要注意的是,关联表的数据主键必须是从1或者0开始,必须连续,且数量必须大于拆分后的条数
brand_name |
---|
BELLE |
思加图 |
他她 |
百思图 |
Bata |
- MySQL数据库中,自带了一个数据库名叫mysql,其中有一个表
help_topic
是从1自增且连续的,数量也能满足大部分场景,唯一有限制的是,你使用的MySQL账户必须有该表的查询权限
-- INSERT INTO test(id, OWNER) VALUES (1,"张三,李四,王二麻子");
SELECT id,substring_index( substring_index( a.OWNER, ';', b.help_topic_id + 1 ), ';',- 1 ) OWNER
FROM test a
JOIN mysql.help_topic b ON b.help_topic_id < (length( a.OWNER ) - length(REPLACE ( a.OWNER, ';', '' )))
- 如果项目中MySQL账户权限比较严格,不能添加自带mysql库中表的权限,可以自己建一个表或者像我在项目中使用临时表,这里由于
brand_info
表主键不是从1开始的,所以这里没有用brand_info
自带的主键id
SELECT substring_index(substring_index(t.brand_name, ',', t1.id + 1), ',', - 1) AS brand_name
FROM tob_contract_info t
INNER JOIN (select (@i:=@i+1) as id from brand_info a,(select @i:=-1) b order by a.id desc) t1
ON t1.id < (length(t.brand_name) - length(REPLACE(t.brand_name, ',', '')) + 1)