首页 > 解决方案 > 将值拆分为多行

问题描述

我有这样的表:

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

标签: mysqlsql

解决方案


在 MySQL 中,可以使用 asubstring_index()和一堆union alls:

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 '%,%,%'

您可以继续在您拥有的最长列表中添加更多子查询。


推荐阅读