MYSQL 拆分字符串和重复行

时间:2021-03-31 15:29:23

标签: mysql sql

我有一个 Mysql 表,看起来像这样:

Col 1.   Col 2.
a        1
b        2
c,d,e    3

我想要做的是运行一个查询,将行替换为 c,d,e 并带有多个断开的行,以便 Select * From 表的结果如下所示:

Col 1.   Col 2.
a        1
b        2
c        3
d        3
e        3

2 个答案:

答案 0 :(得分:1)

如果知道最大数量,可以使用union all

select substring_index(col1, ',', 1) as col1, col2
from t
union all
select substring(substring_index(col1, ',', 2), ',', -1)  as col1, col2
from t
where col1 like '%,%'
union all
select substring(substring_index(col1, ',', 3), ',', -1) as col1, col2
from t
where col1 like '%,%,%';

答案 1 :(得分:0)

使用计数表。例如,我是通过递归 CTE 动态生成的

with recursive nmbs as (
      select 1 n
      union all
      select n+1
      from nmbs
      where n<100
     ),
testdata as (
      select 'a' c1, 1 c2 union all
      select 'b' c1, 2 c2 union all
      select 'c, ddd  , e ,fgh' c1, 3
)     
select c1, c2, trim(replace(substring(substring_index(c1, ',', n), length(substring_index(c1, ',', n-1))+1), ',', '')) s
from testdata 
join nmbs on n <= 1 + length(c1) - length(replace(c1,',',''))
order by c1,n

db<>fiddle