Reputation: 96
In one of my tables fields I contain age ranges. They would be in a format such as
27-51,18-28,10-17
37-55,60-70
1-5,11-16,30-32,60-90
etc
I'm trying to build a SELECT statement where I can search if my given age falls into any of the ranges... something such as
SELECT * from table where age IN (1-5,11-16,30-32,60-90)
However it would search within the given ranges
I can do it if I only have one range using something like...
WHERE age
BETWEEN
SUBSTRING_INDEX(personsAge,"-",1) + 0 AND
SUBSTRING_INDEX(personsAge,"-",-1) + 0
but how can I accomplish this if I have multiple ranges?
Upvotes: 0
Views: 80
Reputation: 5362
This is an answer extending my comment above. I'm assuming that you can create a function:
Attention: This is for Sql Anywhere
. Please adjust the syntax for MySql
(especially the locate
-function where the parameters are switched). The code is not production ready and I left out some validity checks. I'm assuming that the values in the column are all well formatted.
Attention 2: This is one of those cases where someone dumps a terrible database design on you and demands that you solve the problem. Please avoid creating the need for solutions like this.
Function:
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;
Test data:
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');
Call:
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...
Upvotes: 1