mysql根據逗號將一行數據拆分成多行數據


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', '淘寶', '馬雲,孫正義');
  • 三種方式,相同的原理
  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);

    xh表是庫里已有表(可以不是序列表),行數必須大於分割字段的最大逗號數

  • 小結
  1. 序列表必須從0開始,行數與最長逗號有關,行數至少比最長逗號個數加1,可以建0~1000。
  2. 為什么不用MySQL自帶的自增序列表mysql.help_topic?因為好多公司的數據庫是沒有權限操作這些表的, 不能使用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM