首页 > 解决方案 > MySQL:如何检查字段值是否存在于同一个表的逗号分隔字段中

问题描述

我有一个包含两个字符串值的表。第二列col2包含一系列以逗号分隔的字符串。下面是一个简单的例子:

col1            | col2
--------------------------------------------------------
aaa:123.456     | aaa:123.456/,aaa:000.123.456/

我想检索如果我在to000.之后添加的行,它与. 请注意,字符串末尾可能包含查询中需要考虑的内容。aaa:col1col2col2/

IN我使用子句尝试了这个查询:

select *
from table 
where concat('aaa:000',substring_index(col1,'aaa:',-1)) IN (concat(col2,'/'))

我希望我的查询与该行匹配。但事实并非如此。为什么?IN 不应该检查逗号分隔字符串中的每个元素col2吗?如果没有,你能帮我做一个返回行的查询吗?

标签: mysqldatabaserelational-databasemysql-workbench

解决方案


你可以这样做:

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), ',%')

查看演示


推荐阅读