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


    原始数据

     处理结果展示

     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);
  • 相关阅读:
    bzoj 1016 JSOI2008 最小生成树计数
    bzoj 1070 SCOI2007 修车
    bzoj 1042 HAOI2008 硬币购物
    bzoj 1132 POI2008 Tro
    bzoj 1227 SDOI2009 虔诚的墓主人
    bzoj 1024 SCOI2009 生日快乐
    1103 POI2007 大都市meg
    bzoj 1009:[HNOI2008]GT考试
    noip2006T1 能量项链
    bzoj 1006: [HNOI2008]神奇的国度
  • 原文地址:https://www.cnblogs.com/wutanghua/p/14621579.html
Copyright © 2020-2023  润新知