MySQL: 如何检查字段值是否存在于同一 table 中的逗号分隔字段中
MySQL: How to check if a field value exists in a comma separated field in the same table
我有一个包含两个字符串值的 table。第二列 col2
包含一系列以逗号分隔的字符串。下面是一个简单的例子:
col1 | col2
--------------------------------------------------------
aaa:123.456 | aaa:123.456/,aaa:000.123.456/
我想检索如果我在 aaa:
之后添加 000.
到 col1
的行,它匹配 [=14] 中的任何一系列字符串(逗号分隔的字符串) =].请注意,col2
字符串末尾可能包含 /
,这需要在查询中考虑。
我使用 IN
子句尝试了这个查询:
select *
from table
where concat('aaa:000',substring_index(col1,'aaa:',-1)) IN (concat(col2,'/'))
我希望我的查询与该行匹配。但事实并非如此。为什么? IN 不应该检查 col2
中逗号分隔字符串中的每个元素吗?如果没有,你能帮我查询一下 return 行吗?
你可以这样做:
select *
from tablename
where
concat(',', col2, ',') like
concat('%,aaa:000.', substring_index(col1,'aaa:',-1), '/,%')
如果末尾可能有也可能没有 /
那么:
select *
from tablename
where
concat(',', col2, ',') like
concat('%,aaa:000.', substring_index(col1,'aaa:',-1), '/,%')
or
concat(',', col2, ',') like
concat('%,aaa:000.', substring_index(col1,'aaa:',-1), ',%')
见demo
我有一个包含两个字符串值的 table。第二列 col2
包含一系列以逗号分隔的字符串。下面是一个简单的例子:
col1 | col2
--------------------------------------------------------
aaa:123.456 | aaa:123.456/,aaa:000.123.456/
我想检索如果我在 aaa:
之后添加 000.
到 col1
的行,它匹配 [=14] 中的任何一系列字符串(逗号分隔的字符串) =].请注意,col2
字符串末尾可能包含 /
,这需要在查询中考虑。
我使用 IN
子句尝试了这个查询:
select *
from table
where concat('aaa:000',substring_index(col1,'aaa:',-1)) IN (concat(col2,'/'))
我希望我的查询与该行匹配。但事实并非如此。为什么? IN 不应该检查 col2
中逗号分隔字符串中的每个元素吗?如果没有,你能帮我查询一下 return 行吗?
你可以这样做:
select *
from tablename
where
concat(',', col2, ',') like
concat('%,aaa:000.', substring_index(col1,'aaa:',-1), '/,%')
如果末尾可能有也可能没有 /
那么:
select *
from tablename
where
concat(',', col2, ',') like
concat('%,aaa:000.', substring_index(col1,'aaa:',-1), '/,%')
or
concat(',', col2, ',') like
concat('%,aaa:000.', substring_index(col1,'aaa:',-1), ',%')
见demo