MySQL更新和拆分列,其值以逗号分隔

时间:2014-11-17 18:16:47

标签: mysql comma

我有一个数据库,其中一个表有一列有一些特殊数据,但这些数据不符合数据库结构的1NF,2NF,3NF等。

所以在那一列中,我有像“0,3,1,5,20,40”这样的值作为varchar,和 我想编写一个SQL查询来更新这个列并使其像“00,03,01,05,20,40”,也必须注意到很多值都有两位数,这些值我不想添加前面零!

    COLUMN1
    0,3,1,5,20,40,

    MUST LOOKS LIKE
    00,03,01,05,20,40,

我试过用替换功能来做。

  • 问题(1)是,当我添加额外的零时,我想保留前一个值。
  • 问题(2)是必须在逗号之间的值只有一位数时才能完成!

然后,当我使用SQL查询解决此问题时,我将在另一个表中将此列拆分为数据遵循数据库结构。

    ID   VALUE
    1    00
    1    03
    1    01
    1    05
    1    20
    1    40

那么,我该怎么做?

2 个答案:

答案 0 :(得分:2)

我相信这会奏效。它不会考虑多行..所以如果你想要那么你需要按特定的字段进行分组,你要对它进行分组。但这是使用逗号分隔列表时必须处理的内容

SELECT
    GROUP_CONCAT(LPAD(SUBSTRING_INDEX(SUBSTRING_INDEX(column1, ',', n.digit+1), ',', -1), 2, '0')) col
FROM your_table
JOIN
(   SELECT
        SEQ.SeqValue as digit
    FROM
    (   SELECT (TENS.SeqValue + ONES.SeqValue) SeqValue
        FROM(SELECT 0  SeqValue UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) ONES
        CROSS JOIN(SELECT 0 SeqValue UNION ALL SELECT 10 UNION ALL SELECT 20 UNION ALL SELECT 30 UNION ALL SELECT 40 UNION ALL SELECT 50 UNION ALL SELECT 60 UNION ALL SELECT 70 UNION ALL SELECT 80 UNION ALL SELECT 90) TENS
    ) SEQ
) n
ON LENGTH(REPLACE(column1, ',' , '')) <= LENGTH(column1)-n.digit
ORDER BY n.digit

DEMO

这是一个针对column1的多行的演示,其中包含唯一ID,以便您可以按其进行分组。

DEMO

答案 1 :(得分:1)

如果其他答案的优雅方法不起作用,请尝试强力方法。

它查找每边都带有逗号的单个数字,并将其替换为带有前导零的版本,最后在前面查找单个数字(通过在第二个位置查找逗号)和预先挂起零。

update test 
SET column1 = REPLACE(column1,",0,",",00,");
update test 
SET column1 = REPLACE(column1,",1,",",01,");
update test 
SET column1 = REPLACE(column1,",2,",",02,");
update test 
SET column1 = REPLACE(column1,",3,",",03,");
update test 
SET column1 = REPLACE(column1,",4,",",04,");
update test 
SET column1 = REPLACE(column1,",5,",",05,");
update test 
SET column1 = REPLACE(column1,",6,",",06,");
update test 
SET column1 = REPLACE(column1,",7,",",07,");
update test 
SET column1 = REPLACE(column1,",8,",",08,");
update test 
SET column1 = REPLACE(column1,",9,",",09,");
update test 

SET column1 = concat("0",column1)
where mid(column1,2,1) = ",";

<强> DEMO