首页 > 解决方案 > 在特定字符后拆分 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。提前致谢。

标签: mysqlsql

解决方案


您可以使用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。


推荐阅读