mysql - MySQL:如何检查字段值是否存在于同一个表的逗号分隔字段中
问题描述
我有一个包含两个字符串值的表。第二列col2
包含一系列以逗号分隔的字符串。下面是一个简单的例子:
col1 | col2
--------------------------------------------------------
aaa:123.456 | aaa:123.456/,aaa:000.123.456/
我想检索如果我在to000.
之后添加的行,它与. 请注意,字符串末尾可能包含查询中需要考虑的内容。aaa:
col1
col2
col2
/
IN
我使用子句尝试了这个查询:
select *
from table
where concat('aaa:000',substring_index(col1,'aaa:',-1)) IN (concat(col2,'/'))
我希望我的查询与该行匹配。但事实并非如此。为什么?IN 不应该检查逗号分隔字符串中的每个元素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), ',%')
查看演示
推荐阅读
- mysql - 如何用logstash解决mysql连接错误?
- python - 在 Python 中控制字符串到日期的 %y 转换
- linux - Linux 4.18.20 中 NOHZ_FULL 功能的疑惑
- angular - 表情符号的模态在 Angular 中无法正常工作
- c# - 设置器的值始终为空
- database - 我可以在生产服务器中使用基于 NoSQL 文件系统的数据库,例如 NeDB 吗?
- python - 有没有办法根据最大位数修改字符串格式?
- r - 将 R 循环的结果放入数组中会给我错误的值
- r - 在 RMarkdown pdf 中对齐绘图
- azure - 通过 RESTful api 进行 Azure AD 身份验证