MYSQL 一个巧用字符函数做数据筛选的题

 更新时间:2017年5月25日 09:01  点击:1427

问题描述:

结构:

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中存在id=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,之后判断第二个搜索条件应为(即用对应id位置的数字对比):

1690<2000
3502.1>2000
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 |

+---------+---------------------+

[!--infotagslink--]

相关文章