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

Jam*_*son 11 mysql sql

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

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

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

此外,如果有2行以上的距离相同,则随机选择其中一行.

Jam*_*lis 22

一种选择可能是:

select   the_value,
         abs(the_value - 14) as distance_from_test
from     the_table
order by distance_from_test
limit 1
Run Code Online (Sandbox Code Playgroud)

要选择随机记录,可以添加, rand()到该order by子句中.这种方法的缺点是你没有从索引中获得任何好处,因为你必须对派生值进行排序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
Run Code Online (Sandbox Code Playgroud)

  • 我一般会把它写进我写的查询中,以免我后来回来,以为我忘了在:-)中按顺序排序. (2认同)