【问题标题】:DISTINCT Select on comma separated values MySQL [duplicate]DISTINCT 选择逗号分隔值 MySQL [重复]
【发布时间】:2020-12-16 21:02:36
【问题描述】:

目前我有这张表yeast_module,其中有这个字段beer_style

目前,yeast_module 中的每一行都有这个 beer_style 数据

American Amber,American Brown Ale,American India Pale Ale,American Pale Ale,American Porter,American Stout,Barleywine Ale,Belgian Dark Strong Ale,Belgian Table Bier,Belgian Wit,Blonde Ale,Cream Ale,Dusseldorf Altbier,English Brown Ale,English India Pale A

现在,我想知道我是否可以将它拆分并明确选择它。

我正在玩这个命令

SELECT DISTINCT beer_style FROM yeast_module

我的预期输出是

  American Amber,
  American Brown Ale,
  So on..

这是我的示例数据

【问题讨论】:

    标签: mysql sql csv recursive-query unnest


    【解决方案1】:

    您存储数据的方式使此类任务变得乏味(并且本质上效率低下)。将 csv 列表存储在表列中是一种典型的 SQL 反模式,几乎总是应该避免。

    相反,您应该有一个单独的表来表示酵母模块和啤酒风格之间的一对多关系,每个值元组位于单独的行上。

    如果您运行的是 MySQL 8.0,则可以使用递归查询将字符串取消嵌套到行:

    with recursive cte as (
        select 
            substring(beer_style, 1, locate(',', concat(beer_style, ',')) - 1) parsed,
            substring(concat(beer_style, ','), locate(',', concat(beer_style, ',')) + 1) remaining
        from mytable
        union all
        select 
            substring(remaining, 1, locate(',', remaining) - 1),
            substring(remaining, locate(',', remaining) + 1)
        from cte
        where locate(',', remaining) > 0
    )
    select parsed from cte
    

    推荐阅读:Is storing a delimited list in a database column really that bad?

    【讨论】:

    • 到目前为止,我正试图让它变得与众不同,这样我就可以获得beer_style 的所有列表,并为beer_style 的列表制作一个表格,以拥有自己的主键并分配它在yeast_module 上相应地使查询更容易感谢您的回答
    • @RaeIan:同一个查询,select distinct parsed from cte
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    • 2012-08-02
    • 2021-05-18
    • 2019-01-23
    相关资源
    最近更新 更多