如何 select 基于列中的逗号分隔值
how to select based on comma separated values in column
在我的 table 中,其中一列具有逗号分隔值。如果在该列中找到 select 基于一个或两个值的条目,例如
select * from table where tags contains ('ec2' or 'associate')
或包含多个值
select * from table where tags contains 's3' and 'rds'
什么是正确的查询?
您可以使用内置的 find_in_set
功能。
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,%'
如果在tags
中每个,
之后有一个space那么:
select * from table
where
concat(', ', tags, ',') like '%, s3,%'
and
concat(', ', tags, ',') like '%, rds,%'
这可以使用 mysql 正则表达式函数 REGEXP_LIKE :
REGEXP_LIKE(tags, '(^|,)\s*ec2\s*($|,)' )
AND REGEXP_LIKE(tags, '(^|,)\s*associate\s*($|,)' )
因为它不需要修改比较值,所以它可能比使用 LIKE
的解决方案执行得更好。
正则表达式解释:
(^|,)
:字符串的开头或逗号
\s*
: 0个或多个连续空格
ec2
:要搜索的字符串
\s*
: 0个或多个连续空格
($|,)
: 字符串结尾或 comm
如果你想要一个 OR
过滤器而不是 AND
,它可以在单个函数调用中表达,如:
REGEXP_LIKE(tags, '(^|,)\s*((ec2)|(associate))\s*($|,)' )
在我的 table 中,其中一列具有逗号分隔值。如果在该列中找到 select 基于一个或两个值的条目,例如
select * from table where tags contains ('ec2' or 'associate')
或包含多个值
select * from table where tags contains 's3' and 'rds'
什么是正确的查询?
您可以使用内置的 find_in_set
功能。
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,%'
如果在tags
中每个,
之后有一个space那么:
select * from table
where
concat(', ', tags, ',') like '%, s3,%'
and
concat(', ', tags, ',') like '%, rds,%'
这可以使用 mysql 正则表达式函数 REGEXP_LIKE :
REGEXP_LIKE(tags, '(^|,)\s*ec2\s*($|,)' )
AND REGEXP_LIKE(tags, '(^|,)\s*associate\s*($|,)' )
因为它不需要修改比较值,所以它可能比使用 LIKE
的解决方案执行得更好。
正则表达式解释:
(^|,)
:字符串的开头或逗号\s*
: 0个或多个连续空格ec2
:要搜索的字符串\s*
: 0个或多个连续空格($|,)
: 字符串结尾或 comm
如果你想要一个 OR
过滤器而不是 AND
,它可以在单个函数调用中表达,如:
REGEXP_LIKE(tags, '(^|,)\s*((ec2)|(associate))\s*($|,)' )