【问题标题】:how to select based on comma separated values in column如何根据列中的逗号分隔值进行选择
【发布时间】:2018-12-29 23:44:39
【问题描述】:

在我的表中,其中一列具有逗号分隔值。如果在该列中找到,我想根据一两个值选择条目,例如

select * from table where tags contains ('ec2' or 'associate')

或包含多个值

select * from table where tags contains 's3' and 'rds'

什么是正确的查询?

【问题讨论】:

    标签: mysql select tags comma


    【解决方案1】:

    您可以使用内置的find_in_set 函数。

    find_in_set('s3',tags) > 0 and find_in_set('rds',tags) > 0
    

    【讨论】:

    • 该列的类型应该是什么?我应该将其更改为 SET 吗?此外,它似乎没有在逗号后搜索第二个/第三个/.. 值?
    【解决方案2】:

    您可以使用like 运算符:

    select * from table 
    where 
      concat(',', tags, ',') like '%,s3,%' 
      and
      concat(',', tags, ',') like '%,rds,%'
    

    如果在tags 中每个, 后面都有一个空格,那么:

    select * from table 
    where 
      concat(', ', tags, ',') like '%, s3,%' 
      and
      concat(', ', tags, ',') like '%, rds,%'
    

    【讨论】:

      【解决方案3】:

      这可以使用mysql正则表达式函数REGEXP_LIKE来完成:

      REGEXP_LIKE(tags, '(^|,)\s*ec2\s*($|,)' )
      AND REGEXP_LIKE(tags, '(^|,)\s*associate\s*($|,)' )
      

      由于它不需要修改比较值,它可能比使用LIKE的解决方案执行得更好。

      正则表达式解释:

      • (^|,) :字符串开头或逗号
      • \s* : 0 个或多个连续空格
      • ec2:要搜索的字符串
      • \s* : 0 个或多个连续空格
      • ($|,) : 字符串结束或通讯

      如果你想要一个OR 过滤器而不是AND,它可以用一个函数调用来表达,比如:

      REGEXP_LIKE(tags, '(^|,)\s*((ec2)|(associate))\s*($|,)' )
      

      【讨论】:

      • OPs 数据在逗号后有空格,您需要在正则表达式中允许。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-07
      • 1970-01-01
      • 2021-11-24
      相关资源
      最近更新 更多