SQL将值拆分为多行
问题描述:
我有桌子:
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
请在此处看到小提琴.
如果无法创建表,则可以采用以下解决方案:
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
一个小提琴示例是此处.