我的桌子像:
id | col1 | col2 | col3
1 | 1,2 | 2,5 | 6,3
2 | 3,5,6|1,2,3 |9,8,7
我想要这样的输出:
id | newCol1 | newCol2 | newCol3
1 | 1 | 2 | 6
1 | 2 | 5 | 3
2 | 3 | 1 | 9
2 | 5 | 2 | 8
2 | 6 | 3 | 7
答案 0 :(得分:0)
在MySQL中,您可以使用substring_index()
和一堆union all
:
select id,
substring_index(col1, ',', 1) as newcol1,
substring_index(col2, ',', 1) as newcol2,
substring_index(col3, ',', 1) as newcol3
from t
union all
select id,
substring_index(substring_index(col1, ',', 2), ',', -1) as newcol1,
substring_index(substring_index(col2, ',', 2), ',', -1) as newcol2,
substring_index(substring_index(col3, ',', 2), ',', -1) as newcol3
from t
where col1 like '%,%'
union all
select id,
substring_index(substring_index(col1, ',', 3), ',', -1) as newcol1,
substring_index(substring_index(col2, ',', 3), ',', -1) as newcol2,
substring_index(substring_index(col3, ',', 3), ',', -1) as newcol3
from t
where col1 like '%,%,%'
您可以继续在您拥有的最长列表中添加更多子查询。