Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get nearest value from database in mysql

I am using mySQL and CodeIgniter. I have some floating point numbers in my database such as

  • 8.3456
  • 8.5555
  • 4.5556

I want to...

SELECT * FROM table WHERE value = $myvalue

but I can't use value = $myvalue in my SELECT query because $myvalue is not exactly equal to database values. I need to get the nearest value to $myvalue from database.

If $myvalue is 5 I want to select the value 4.5556.

How can I do this in mySQL?

like image 390
Kanishka Panamaldeniya Avatar asked Sep 01 '11 10:09

Kanishka Panamaldeniya


People also ask

How do I find the nearest value in SQL?

SQL uses the CEILING function to perform this computation. It takes a single argument: the column whose values you'd like to round up to the nearest integer.

What is Row_count () in MySQL?

ROW_COUNT() returns the number of rows updated, inserted or deleted by the preceding statement. This is the same as the row count that the mysql client displays and the value from the mysql_affected_rows() C API function.

What is %s and %D in MySQL?

12 years, 10 months ago. it's for php to know how to handle the parameters, %d – the argument is treated as an integer, and presented as a (signed) decimal number. %s – the argument is treated as and presented as a string. in your examples, $slug is a string and $this->id is an integer.

How do I find a specific data in MySQL?

MySQL WorkbenchThere is a Schemas tab on the side menu bar, click on the Schemas tab, then double click on a database to select the database you want to search. Then go to menu Database - Search Data, and enter the text you are searching for, click on Start Search.


2 Answers

select * 
from table 
order by abs(value - $myvalue)
limit 1
like image 153
Bohemian Avatar answered Sep 18 '22 14:09

Bohemian


(
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

This may look counter-intuitive but the speed will be greater than the other queries shown so far.

This is due to the fact that a greater than and less than query is quicker.

Then doing an ABS on two values is nothing.

This will give you the quickest return in a single query I can think of.

Doing an ABS on a whole table will be slow as it will scan the whole table.

like image 28
Graham Ritchie Avatar answered Sep 18 '22 14:09

Graham Ritchie