4

所以目前我的表中有数据

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, '');

但似乎我必须手动指定索引。

4

2 回答 2

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);

于 2019-09-04T09:50:35.560 回答
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]>
于 2019-01-25T14:15:50.347 回答