使用mysql将逗号分隔值从表列拆分为行?

时间:2021-06-13 16:58:50

I found the post which has the column with 3 values seperated by commas. I will have more than 3 values seperated by commas . For example,

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

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

Is it possible to split string city_id and make it into rows using mysql query like below

是否可以使用如下所示的mysql查询拆分字符串city_id并使其成为行

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

If yes, Kindly give some advice ....

如果是,请提供一些建议......

1 个解决方案

#1


3  

Try this

尝试这个

  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

FIDDLE DEMO

Output:

输出:


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

#1


3  

Try this

尝试这个

  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

FIDDLE DEMO

Output:

输出:


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