zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    域名证书文件包含两段证书
    关于docker的scratch镜像与helloworld
    JS实现网站内容的禁止复制和粘贴、另存为
    使用chromedriver实现豆瓣网页的全网页截图
    Python Tornado初学笔记之数据库(二)
    Python Tornado初学笔记之表单与模板(一)
    Redis中sds 模块的 API
    原码、补码、反码、移码之间的换算
    Python中的位运算
    Python中进制的转换
  • 原文地址:https://www.cnblogs.com/wutanghua/p/14621579.html
Copyright © 2011-2022 走看看