Anders
Anders

Reputation: 531

Find closest match by number in MySQLI

I'm working on a PHP / MySQLI application, where the user needs to input a number, and then it should get the 5 closest records to that given number.

Can this be done by a simple SQL string, or do I need to get all the numbers into an array, and then match by that..?

Thanks!

Upvotes: 2

Views: 177

Answers (1)

Nicklas Kevin Frank
Nicklas Kevin Frank

Reputation: 6337

This is possible through following query:

SELECT * FROM [table] 
ORDER BY ABS([column] - [userinput])
LIMIT 5

However, if you could provide more information we would also be able to provide you with a better solution. This query is not very scalable and will after a couple of thousand rows start to get slow.

How are you going to use this query? Are we talking thousands of records? What kind of numbers is it? Is there some pattern? All such questions would allow for a more precise solution that could possible scale better with your system.

Upvotes: 2

Related Questions