mysql - 在特定字符后拆分 SQL 中的值
问题描述
我有一个包含一列的表格:
Val A
Val B
Val C,Val B,Val D
Val A,Val F,Val A
我的问题在这种情况下如何在特定字符“”之后拆分值,以便我每行只能有一个,如下所示:
Val A
Val B
Val C
Val B
Val D
Val A
Val F
Val A
如果它很重要,我不知道,但我正在使用 MySql Workbench。提前致谢。
解决方案
您可以使用substring_index()
. 一种方法是:
select substring_index(col, ';', 1)
from t
union all
select substring_index(substring_index(col, ';', 2), ';', -1)
from t
where col like '%;%'
union all
select substring_index(substring_index(col, ';', 3), ';', -1)
from t
where col like '%;%;%';
您需要添加一个单独的子查询,直到任何行中的最大元素数。
编辑:
我真的不喜欢副本中的答案。我会推荐一个递归CTE:
with recursive cte as (
select col as part, concat(col, ',') as rest, 0 as lev
from t
union all
select substring_index(rest, ',', 1),
substr(rest, instr(rest, ',') + 1),
lev + 1
from cte
where rest <> '' and lev < 5
)
select part
from cte
where lev > 0;
这是一个 db<>fiddle。
推荐阅读
- sql-server - 将数据从 SQL Server 导出为 CSV 时,位列不断转换为布尔值
- javascript - 获取特定元素数组的元素的总和
- arrays - 为什么从函数内部计算数组的大小不正确?
- python - 在python中将时间戳转换为日期时间
- java - 如何使用方法通道将自定义 POJO 或 DTO 对象从颤振传递到 Android?
- numpy - 如何解决Expected all tensor to be on the same device且不能将CUDA tensor转换为numpy之间的矛盾
- laravel - Laravel 和惯性.js 文件下载
- php - 用户名和密码不匹配输出
- azure - Azure Web 服务 IP 地址
- javascript - 与以下代码段等效的反应挂钩是什么?