Nearest Value in the Database table

I want to Find the nearest numeric match in a database to what a user has inputed in php. The Database value can be multipled with an integer to find the near value to user Input.

For Ex: Database has the following Pallets:

950, 900, 1070

User Input a Value: 2000

Not the System should check:

950 * 2 = 1900
900 *2 = 1800
1070 * 2 = 2140

So the nearest value to 2000 is 1900. Any Help will be appreciated.

Upvotes: 0

Views: 65

Answers (2)

nithinTa
nithinTa

Reputation: 1642

Try this query, also replace 2000 with user input.

SELECT your_column, abs( 2000 MOD your_column) ) as diff
FROM `mytable`
ORDER BY diff
LIMIT 1

Upvotes: 1

Ravi Chauhan
Ravi Chauhan

Reputation: 1458

SELECT your_column, abs( $_POST['form_field_name']-(your_column*2) ) as setcustomcolumn FROM `rablename` order by columnname LIMIT 1

Upvotes: 0

Related Questions