MySQL利用字符函数实现逗号分隔数据的关联筛选
问题描述:
数据结构:
测试表 test 包含 col1 和 col2 两个字符型字段。两列内容均由逗号分隔的三个数字组成,且位置一一对应。
例如 col1 内容为 '26,59,6',col2 为 '1502.5,1690,2276.77'。其中 26 对应 1502.5,59 对应 1690,6 对应 2276.77。
搜索条件:
假设选定 ID 为 59,并设定阈值 2000。需求是找出 col1 中存在 59 的记录,同时验证 col2 中对应位置的数值是否小于 2000(即 1690 < 2000)。
举例说明:
若存在以下三条记录,需筛选出 ID 为 59 且对应值小于 2000 的数据:
26,59,6 | 1502.5,1690,2276.77 59,33,6 | 3502.1,1020,2276.77 22,8,59 | 1332.6,2900,1520.77
首先确认记录中存在 ID 59,随后判断第二个条件:取 col1 中 59 所在位置对应的 col2 数值进行对比。
第一条记录对应值为 1690,满足 1690 < 2000; 第二条记录对应值为 3502.1,不满足 3502.1 > 2000; 第三条记录对应值为 1520.77,满足 1520.77 < 2000。
drop table test;
create table test ( col1 varchar(100),col2 varchar(100));
insert test select
'26,59,6', '1502.5,1690,2276.77' union all select
'59,33,6', '3502.1,1020,2276.77' union all select
'22,8,59', '1332.6,2900,1520.77';
select col1,col2
from (select *,find_in_set('59',col1) as rn from test) k
where substring_index(concat(',',substring_index(col2,',',rn)),',',-1)
<'2000';
+---------+---------------------+
| col1 | col2 |
+---------+---------------------+
| 26,59,6 | 1502.5,1690,2276.77 |
| 22,8,59 | 1332.6,2900,1520.77 |
+---------+---------------------+