【问题标题】:SQL (Maria DB) split string separated by comma to rowsSQL(Maria DB)将用逗号分隔的字符串拆分为行
【发布时间】:2020-10-20 22:13:31
【问题描述】:

我有这个专栏:

names
John, Mary
Joseph
Eleanor, Sophia, Dani

我想要这个输出:

names
John
Mary
Joseph
Eleanor
Sophia
Dani

它应该包括 SUBSTRING_INDEX 函数

【问题讨论】:

  • 这不是发布您的问题并获得答案的门户。您必须发布您尝试过的内容,我们的社区成员会帮助您纠正错误。这不是一个不亲自尝试就可以得到答案的地方。

标签: sql string csv mariadb recursive-query


【解决方案1】:

您可以使用递归 CTE:

with recursive cte as (
      select '            ' as name, concat(names, ',') as names, 1 as lev
      from t
      union all
      select substring_index(names, ',', 1),
             substr(names, instr(names, ',') + 2), lev + 1
      from cte
      where names like '%,%'
     )
select name
from cte
where lev > 1;

Here 是一个 dbfiddle。

【讨论】:

    【解决方案2】:

    一个选项使用递归查询:

     with recursive
        data as (select concat(names, ', ') names from mytable),
        cte as (
            select 
                substring(names, 1, locate(', ', names) - 1) word,
                substring(names, locate(', ', names) + 2) names
            from data
            union all
            select 
                substring(names, 1, locate(', ', names) - 1) word,
                substring(names, locate(', ', names) + 2) names
            from cte
            where locate(', ', names) > 0
        )
    select word from cte
    

    Demo on DB Fiddle

    |词 | | :-------- | |约翰 | |约瑟夫 | |埃莉诺 | |玛丽 | |索菲亚 | |丹妮 |

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      • 2015-03-07
      • 2018-12-21
      • 1970-01-01
      • 2019-07-29
      相关资源
      最近更新 更多