首页 > 数据库技术 > 详细

MySQL根据逗号将一行数据拆成多行数据

时间:2021-04-06 15:00:52      阅读:22      评论:0      收藏:0      [点我收藏+]

原始数据

技术分享图片

 

 

 处理结果展示

技术分享图片

 

 

 DDL

CREATE TABLE `company` (
`id` int(20) DEFAULT NULL,
`name` varchar(100) DEFAULT NULL,
`shareholder` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DML

INSERT INTO `company` VALUES (1, 阿里巴巴, 马云); 
INSERT INTO `company` VALUES (2, 淘宝, 马云,孙正义);
INSERT INTO `company` VALUES (2, 淘宝, 马云,孙正义,茅五);

三种方式,相同的原理

1.使用MySQL库中的自增序列表

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
)

2.自建自增序列表

CREATE TABLE `addself` (
`id` int(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `addself` VALUES (0); 
INSERT INTO `addself` VALUES (1);
INSERT INTO `addself` VALUES (2);
INSERT INTO `addself` VALUES (3);
INSERT INTO `addself` VALUES (4);
SELECT
    a.id,
    a.NAME,
    substring_index(
        substring_index(
            a.shareholder,
            ,,
            b.id+ 1
        ),
        , ,- 1
    ) AS shareholder
FROM
    company a
JOIN addself b ON b.id< (
    length(a.shareholder) - length(
        REPLACE (a.shareholder, ,, ‘‘)
    ) + 1
)

3.以数据库里已有表,构建自增序列表

select a.ID,a.name,substring_index(substring_index(a.shareholder,,,b.id+1),,,-1) shareholder
from
company a
join
(SELECT (@ROW :=@Row + 1) as id FROM xh,(SELECT @Row:=-1) zz) b
on b.id < (length(a.shareholder) - length(replace(a.shareholder,,,‘‘))+1);

 

MySQL根据逗号将一行数据拆成多行数据

原文:https://www.cnblogs.com/wutanghua/p/14621579.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!