gpt4 book ai didi

php - 使用 mysql 将表列中的逗号分隔值拆分为行?

转载 作者:行者123 更新时间:2023-11-29 04:50:05 25 4
gpt4 key购买 nike

我找到了 post其中包含由逗号分隔的 3 个值的列。我将有 3 个以上的值,用逗号分隔。例如,

ID    CITY_ID
--------------
1 12,18,16,17,35
2 12,16
....
--------------

是否可以像下面这样使用 mysql 查询拆分字符串 city_id 并将其放入行中

  ID   CITY_ID
-------------
1 12
1 18
1 16
....
2 16
....
--------------

如果是,请给点建议....

最佳答案

试试这个

  SELECT ID,SUBSTRING_INDEX(SUBSTRING_INDEX(t.CITY_ID, ',', n.n), ',', -1) value
FROM Table1 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
ORDER BY n
) n
WHERE n.n <= 1 + (LENGTH(t.CITY_ID) - LENGTH(REPLACE(t.CITY_ID, ',', '')))
ORDER BY ID,value

FIDDLE DEMO

输出:


ID  VALUE
1 12
1 16
1 17
1 18
1 35
2 12
2 16

关于php - 使用 mysql 将表列中的逗号分隔值拆分为行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12872277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com