gpt4 book ai didi

sql - 使用 MySQL 查询选择最接近的数值

转载 作者:IT王子 更新时间:2023-10-29 00:30:47 25 4
gpt4 key购买 nike

这可能比我做的要容易,但基本上我需要做的是选择列中具有最接近数字的行作为指定值。例如:

数据库中指定列中 3 行的值列表:10、15、16

如果我指定我想要最接近 14 的行,它会选择 15 的行。

此外,如果有 2+ 行距离相同,则随机选择其中之一。

最佳答案

一个选项是这样的:

select   the_value,
abs(the_value - 14) as distance_from_test
from the_table
order by distance_from_test
limit 1

要选择一条随机记录,可以在order by子句中添加, rand()。这种方法的缺点是您无法从索引中获得任何好处,因为您必须对派生值 distance_from_test 进行排序。

如果您在 the_value 上有一个索引,并且您放宽了在平局情况下结果是随机的要求,您可以执行一对有限范围查询来选择紧接在上面的第一个值测试值和紧接在测试值下方的第一个值,并选择最接近测试值的值:

(
select the_value
from the_table
where the_value >= 14
order by the_value asc
limit 1
)
union
(
select the_value
from the_table
where the_value < 14
order by the_value desc
limit 1
)
order by abs(the_value - 14)
limit 1

关于sql - 使用 MySQL 查询选择最接近的数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1634725/

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