我有一个包含两个字符串值的表。第二列col2
包含一系列逗号分隔的字符串。以下是一个简单的例子:
col1 | col2
--------------------------------------------------------
aaa:123.456 | aaa:123.456/,aaa:000.123.456/
我想检索行,如果我在000.
之后将aaa:
添加到col1
,它会匹配col2
中的任何字符串系列(逗号分隔的字符串)。请注意,col2
字符串最后可能包含/
,需要在查询中考虑。
我使用IN
子句尝试了这个查询:
select *
from table
where concat('aaa:000',substring_index(col1,'aaa:',-1)) IN (concat(col2,'/'))
我希望我的查询与行匹配。但事实并非如此。为什么?是不是应该检查col2
中逗号分隔字符串中的每个元素?如果没有,你能帮我查一下返回行的查询吗?
你可以这样做:
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