我有一个数据库,其中一个表有一列有一些特殊数据,但这些数据不符合数据库结构的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,
我试过用替换功能来做。
然后,当我使用SQL查询解决此问题时,我将在另一个表中将此列拆分为数据遵循数据库结构。
ID VALUE
1 00
1 03
1 01
1 05
1 20
1 40
那么,我该怎么做?
答案 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
这是一个针对column1的多行的演示,其中包含唯一ID,以便您可以按其进行分组。
答案 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 强>