PDA

View Full Version : two closest and two just past a number in PHP <> MySQL


edge
4th September 2008, 15:30
Hi all,

I hope someone here can show me how to do this.

I have the following data in a MySQL database.

...
...
2454
4387
2763
1998
4385
2501
2529
2409
2503
3082
...
...

Reading all the data is no problem, but I would like to show the 1st two numbers closest to a requested number, and the 1st two closest past the requested number.

Lets say the requested number is: 2500

So now I want the result to show the two closest in front of 2500 (in the example above that would be 2454 and 2763), AND the two closest just past 2500 (that would be 2501 and 2503)

Anyone here who might know how I could do this?

Thank you for any info on this.

Ben
4th September 2008, 15:49
You can do it with a query like this:


SELECT * FROM `test2` WHERE num < 2500 order by num desc limit 2


It sorts the result descending so that the biggest numbers are on top, and cuts 2 from the top.
Just change desc into asc and < to > if you want to have the next 2 bigger than 2500.

edge
4th September 2008, 16:06
You can do it with a query like this:



It sorts the result descending so that the biggest numbers are on top, and cuts 2 from the top.
Just change desc into asc and < to > if you want to have the next 2 bigger than 2500.

Looks like that will do the job :-)

Thank you.