mysql - 将值拆分为多行
问题描述
我有这样的表:
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
解决方案
在 MySQL 中,可以使用 asubstring_index()
和一堆union all
s:
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 '%,%,%'
您可以继续在您拥有的最长列表中添加更多子查询。
推荐阅读
- typescript - TypeScript:让库的用户定义类型
- mysql - MySQL SELECT * 在 Unicode 上失败
- node.js - node.js 和 express 的区别
- python - 通过单击页面中的每个超链接来抓取网站
- r - 在 R 中满足另一个条件时(即当另一个变量是特定值时)需要帮助用 NA 替换值
- javascript - props.images.map 不是函数(函数组件)
- entity-framework - 在 EF Core 中的每条记录上自动设置创建和修改日期的问题
- java - Spring将实例化委托给另一个线程
- python - 如何将单行数据框连接到更大的数据框?当前获取“TypeError:预期的元组,得到str”
- c# - 如何通过使用按钮将学生对象添加到数组中?