gpt4 book ai didi

mysql 搜索逗号列表的数字范围

转载 作者:行者123 更新时间:2023-11-29 09:50:26 24 4
gpt4 key购买 nike

在我的一个表字段中,我包含年龄范围。它们的格式如

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...

关于mysql 搜索逗号列表的数字范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54913942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com