所以目前我的表中有数据
Numbers (Varchar 255)
111|1232|234
434|234
12546|3243|3434
23434|34
35465|3434
当前,该列为VARCHAR,但我打算将其转换为JSON字段,因此在转换该字段之前,我尝试将它们设置为json或数组。
我尝试遵循
CREATE FUNCTION SPLIT_STRING(str VARCHAR(255), delim VARCHAR(12), pos INT)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(str, delim, pos),
LENGTH(SUBSTRING_INDEX(str, delim, pos-1)) + 1),
delim, '');
但是似乎我必须手动指定索引。
答案 0 :(得分:1)
对于这样的简单结构,您可以尝试使用replace和concat
select cast(concat('[', replace('1|2|3', '|', ', '), ']') as JSON);
-- for convert to text
select cast(concat('["', replace('1|2|3', '|', '", "'), '"]') as JSON);
答案 1 :(得分:0)
您可以使用如下查询:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX( CONCAT('|',n.Numbers,'|') , '|', i.id), '|', -1) AS nums
FROM num n
CROSS JOIN (
SELECT 2 AS id UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 ) AS i
HAVING nums <> ''
ORDER BY n.id
样品
MariaDB [num]> select * from num;
+----+--------------+
| id | Numbers |
+----+--------------+
| 1 | 111|1232|234 |
| 2 | 2|44|55|999 |
| 3 | NULL |
| 4 | 99|11 |
+----+--------------+
4 rows in set (0.000 sec)
MariaDB [num]> SELECT SUBSTRING_INDEX(SUBSTRING_INDEX( CONCAT('|',n.Numbers,'|') , '|', i.id), '|', -1) AS nums
-> FROM num n
-> CROSS JOIN (
-> SELECT 2 AS id UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 ) AS i
-> HAVING nums <> ''
-> ORDER BY n.id
-> ;
+------+
| nums |
+------+
| 111 |
| 1232 |
| 234 |
| 2 |
| 44 |
| 55 |
| 999 |
| 99 |
| 11 |
+------+
9 rows in set (0.001 sec)
MariaDB [num]>