如何在mysql中从数据库中获取最接近的值

时间:2011-09-01 10:49:03

标签: mysql sql codeigniter select

我正在使用mySQLCodeIgniter。我的数据库中有一些浮点数,例如

  • 8.3456
  • 8.5555
  • 4.5556

我想......

SELECT * FROM table WHERE value = $myvalue

但我无法在SELECT查询中使用value = $myvalue,因为$myvalue与数据库值不完全相同。我需要从数据库中获取最接近$myvalue的值。

如果$myvalue为5,我想选择值4.5556

我如何在mySQL中执行此操作?

11 个答案:

答案 0 :(得分:16)

select * 
from table 
order by abs(value - $myvalue)
limit 1

答案 1 :(得分:14)

假设您有10%的容忍度(+/-),您可以尝试以下方式:

select * from table 
where value >= ($myvalue * .9) and value <= ($myvalue * 1.1) 
order by abs(value - $myvalue) limit 1

稍微更新其他人的窃取 - 这应该在假定的容差范围内返回最近的结果。 (另外,我只是注意到哪里不正确,道歉 - 现在应该可以了。)

答案 2 :(得分:4)

(
select   *
from     table
where    value >= $myvalue
order by value asc
limit 1
)
union
(
select   *
from     table
where    value < $myvalue
order by value desc
limit 1
)
order by abs(value - $myvalue)
limit 1

这看起来可能违反直觉,但速度会比目前为止显示的其他查询更快。

这是因为greater thanless than查询更快。

然后对两个值进行ABS就没有了。

这将为您提供我能想到的单个查询中最快的回报。

在整个表格上执行ABS会很慢,因为它会扫描整个表格。

答案 3 :(得分:2)

从以下内容中获取第一个值:

select * from table order by abs(value - $myvalue);

答案 4 :(得分:2)

获取类似于$ val的最大值:

SELECT * FROM tab WHERE val <= $val ORDER BY val DESC LIMIT 1

获得类似于$ val的最小值:

SELECT * FROM tab WHERE val >= $val ORDER BY val LIMIT 1

在任一方向上获得与$ val类似的最接近值:

SELECT * FROM tab ORDER BY abs(val - $val) LIMIT 1

答案 5 :(得分:0)

SELECT * FROM table1 ORDER BY ABS(value - '$myvalue') LIMIT 1 

答案 6 :(得分:0)

阅读本页http://dev.mysql.com/doc/refman/5.1/en/mathematical-functions.html#function_round

但你的选择看起来像这样

select value from table where ROUND(value) = $myvalue 

答案 7 :(得分:0)

不幸的是,我认为您的数据库可能会对涉及abs的解决方案进行全表扫描,因此一旦您的表增长,它们将会非常慢。可以在此earlier thread中找到快速运行的解决方案。

答案 8 :(得分:0)

SELECT number, ABS( number - 2500 ) AS distance
FROM numbers
ORDER BY distance
LIMIT 6

Selecting closest values in MySQL

答案 9 :(得分:0)

试试这个:

SELECT *,abs((columnname -Yourvalue)) as near
  FROM table
 WHERE order by near limit 0,1

答案 10 :(得分:0)

在我的情况下,我正在使用浏览器的地理位置,并尝试根据表格中的坐标查找最近的城市/州。

表结构:

id    zipcode    city_state   lat    lon
1     12345      Example, GA  85.3   -83.2

建议在使用前大力测试-可能需要进行一些调整,但我还是以此为出发点

SELECT city_state, 
   zipcode, 
   ( Abs( lat - -33.867886 ) 
     + Abs( lon - -63.987) ) AS distance
FROM   zipcodes 
ORDER  BY distance 
LIMIT  1;  

对于laravel用户:

$city = Zipcodes::selectRaw
    ('city_state, zipcode,  ( ABS( lat - ? ) + ABS( lon - ?) ) AS distance', [$lat, $lon])
        ->orderBy('distance')
        ->first();

echo $city->city_state

希望有一天能对某人有所帮助。

相关问题