SQL 将值拆分为多行

2021-11-20 00:00:00 csv sql delimiter mysql

我有桌子:

id | name    
1  | a,b,c    
2  | b

我想要这样的输出:

id | name    
1  | a    
1  | b    
1  | c    
2  | b

推荐答案

如果您可以创建一个数字表,其中包含从 1 到要拆分的最大字段的数字,您可以使用如下解决方案:

If you can create a numbers table, that contains numbers from 1 to the maximum fields to split, you could use a solution like this:

select
  tablename.id,
  SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name
from
  numbers inner join tablename
  on CHAR_LENGTH(tablename.name)
     -CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
order by
  id, n

请参阅 fiddle 此处.

Please see fiddle here.

如果您无法创建表,那么解决方案可以是:

If you cannot create a table, then a solution can be this:

select
  tablename.id,
  SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name
from
  (select 1 n union all
   select 2 union all select 3 union all
   select 4 union all select 5) numbers INNER JOIN tablename
  on CHAR_LENGTH(tablename.name)
     -CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
order by
  id, n

示例小提琴是这里.

相关文章