我有价值观
[abc,123,aed,ghi]
我想在mysql中单独拆分值。
结果应该是这样的
column1 column2 column3 column4
abc 123 aed ghi
答案 0 :(得分:1)
关系数据库和非原子数据设计很差。但你可以使用:
SELECT ID,
MAX(CASE WHEN N = 1 THEN sub.val END) AS Column1,
MAX(CASE WHEN N = 2 THEN sub.val END) AS Column2,
MAX(CASE WHEN N = 3 THEN sub.val END) AS Column3,
MAX(CASE WHEN N = 4 THEN sub.val END) AS Column4
FROM
(
SELECT ID, SUBSTRING_INDEX(SUBSTRING_INDEX(t.HashTag, ',', n.n), ',', -1) AS val, N
FROM (SELECT ID, Substring(my_csv_column, 2, LENGTH(my_csv_column) - 2) AS HashTag FROM my_non_normalized_table) AS t
CROSS JOIN
(
SELECT a.N + b.N * 10 + 1 n
FROM
(SELECT 0 AS N 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) a
,(SELECT 0 AS N 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) b
) n
WHERE n.n <= 1 + (LENGTH(t.HashTag) - LENGTH(REPLACE(t.HashTag, ',', '')))
) sub
GROUP BY ID;
的 SqlFiddleDemo
强>
输出:
╔═════╦══════════╦══════════╦══════════╦═════════╗
║ ID ║ Column1 ║ Column2 ║ Column3 ║ Column4 ║
╠═════╬══════════╬══════════╬══════════╬═════════╣
║ 1 ║ abc ║ 123 ║ aed ║ ghi ║
║ 2 ║ efg ║ cde ║ (null) ║ (null) ║
╚═════╩══════════╩══════════╩══════════╩═════════╝
您应该阅读有关数据规范化和1NF
。
答案 1 :(得分:0)
不幸的是,MySQL没有分裂字符串功能。然而 您可以为此创建user defined function,例如一个 在下面的文章中描述:
Federico Cargnelutti的
- MySQL Split String Function
使用该功能,您可以按如下方式构建查询:
void test(int... values){}