在我的一个表字段中,我包含年龄范围。它们的格式如下
27-51,18-28,10-17
37-55,60-70
1-5,11-16,30-32,60-90
etc
我正在尝试构建一个SELECT语句,我可以搜索我的给定年龄是否属于任何范围......例如
SELECT * from table where age IN (1-5,11-16,30-32,60-90)
但是它会在给定范围内搜索
如果我只使用类似的东西,我可以做到这一点......
WHERE age
BETWEEN
SUBSTRING_INDEX(personsAge,"-",1) + 0 AND
SUBSTRING_INDEX(personsAge,"-",-1) + 0
但是如果我有多个范围怎么能完成这个呢?
这是一个扩展我的评论的答案。我假设你可以创建一个函数:
注意:这是为了Sql Anywhere
。请调整MySql
的语法(尤其是切换参数的locate
函数)。代码没有生产就绪,我遗漏了一些有效性检查。我假设列中的值都格式正确。
注意2:这是有人向您转储可怕的数据库设计并要求您解决问题的情况之一。请避免创建对此类解决方案的需求。
功能:
CREATE FUNCTION "DBA"."is_in_range"(age_range varchar(255), age int)
returns int
begin
declare pos int;
declare pos2 int;
declare strPart varchar(50);
declare strFrom varchar(10);
declare strTo varchar(10);
declare iFrom int;
declare iTo int;
while 1 = 1 loop
set pos = locate(age_range, ',');
if pos = 0 then
-- no comma found in the rest of the column value -> just take the whole string
set strPart = age_range;
else
-- take part of the sting until next comma
set strPart = substr(age_range, 1, pos - 1);
end if;
-- we are parsing the min-max part and do some casting to compare with an int
set pos2 = locate(strPart, '-');
set strFrom = substr(strPart, 1, pos2 - 1);
set strTo = substr(strPart, pos2 + 1);
set iFrom = cast(strFrom as int);
set iTo = cast(strTo as int);
if age between iFrom and iTo then
return 1;
end if;
-- if at end of age_range then quit
if pos = 0 then
return 0;
end if;
-- get the next part of the string after the comma
set age_range = substr(age_range, pos + 1);
set pos = locate(age_range, ',', pos);
end loop;
return 0;
end;
测试数据:
create local temporary table #tmpRanges (ident int, age_range varchar(255));
insert into #tmpRanges (ident, age_range) values (1, '27-51,18-28,10-17');
insert into #tmpRanges (ident, age_range) values (2, '37-55,60-70');
insert into #tmpRanges (ident, age_range) values (3, '1-5,11-16,30-32,60-90');
insert into #tmpRanges (ident, age_range) values (4, '1-50');
呼叫:
select * from #tmpRanges where is_in_range(age_range, 51) = 1;
select * from #tmpRanges where is_in_range(age_range, 10) = 1;
select * from #tmpRanges where is_in_range(age_range, 9) = 1;
etc...