MySQL:如何检查同一个表中逗号分隔字段中是否存在字段值

问题描述 投票:0回答:1

我有一个包含两个字符串值的表。第二列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中逗号分隔字符串中的每个元素?如果没有,你能帮我查一下返回行的查询吗?

mysql database relational-database mysql-workbench
1个回答
0
投票

你可以这样做:

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

© www.soinside.com 2019 - 2024. All rights reserved.