2017-04-18 60 views
0

我有如下表:SQL轉換一行行分隔字符串各行

id, names, group 
1, 'mike\nsteve', 1 
2, 'maria\npeter\nlisa', 1 

與換行符的名字被保存爲一個字符串。 我想移動的所有名稱以不同的行中另一個表:

id, name, group 
1, mike, 1 
2, steve, 1 
3, maria, 1 
4, peter, 1 
5, lisa, 1 

我可以在單個查詢做到這一點?

回答

0

我認爲最簡單的方法是union all

select id, substring_index(names, '\n', 1), group 
from t 
union all 
select id, substring_index(substring_index(names, '\n', 2), '\n', -1), group 
from t 
where names like '%\n%' 
union all 
select id, substring_index(substring_index(names, '\n', 3), '\n', -1), group 
from t 
where names like '%\n%\n%' 
. . . 

您將需要添加更多的子查詢到字符串名稱的最大數量。

您可以使用create table asinsert into . . .將這些放在另一個表中。

+0

OP想要將這些插入到另一個表中。 –