Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何基于列中逗号分隔的值进行选择_Mysql_Select_Tags_Comma - Fatal编程技术网

Mysql 如何基于列中逗号分隔的值进行选择

Mysql 如何基于列中逗号分隔的值进行选择,mysql,select,tags,comma,Mysql,Select,Tags,Comma,在我的表中,其中一列有逗号分隔的值。如果在该列中找到一个或两个值,我希望根据该值选择条目,如 select * from table where tags contains ('ec2' or 'associate') 或包含多个值 select * from table where tags contains 's3' and 'rds' 什么是正确的查询 您可以使用内置功能 find_in_set('s3',tags) > 0 and find_in_set('rds',tags)

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

select * from table where tags contains ('ec2' or 'associate')
或包含多个值

select * from table where tags contains 's3' and 'rds'
什么是正确的查询

您可以使用内置功能

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

您可以使用
like
操作符:

select * from table 
where 
  concat(',', tags, ',') like '%,s3,%' 
  and
  concat(',', tags, ',') like '%,rds,%'
如果在每个
后面的
标签中有一个空格,则:

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

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

由于它不需要修改比较的值,因此它的性能可能比使用类似
的解决方案要好

正则表达式解释:

  • (^ |,)
    :字符串或逗号的开头
  • \s*
    :0个或多个连续空格
  • ec2
    :要搜索的字符串
  • \s*
    :0个或多个连续空格
  • ($|,)
    :字符串或命令的结尾
如果希望使用
过滤器而不是
,则可以在单个函数调用中表示,如:

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

列的类型应该是什么?我应该把它改成SET吗?而且它似乎没有搜索第二个/第三个/。。逗号后的值?@SomeJavaGuy您需要使用
REPLACE(tags,,“”)
删除
标记中的所有空白
value for
FIND_IN_SET
要正常工作如果数据在逗号后有空格,您需要在正则表达式中考虑到这一点。
REGEXP_LIKE(tags, '(^|,)\s*((ec2)|(associate))\s*($|,)' )