943,718 Members | Top Members by Rank

Ad:
  • PHP Discussion Thread
  • Unsolved
  • Views: 863
  • PHP RSS
Mar 8th, 2008
0

nearest number

Expand Post »
If you have a column, of data type = INT, with the following numbers
as separate rows.
1
3
4
5
7
10


How can you write a sql statement where you can calculate the
nearest number to any give input.
Example , if the input is 9 ? (the answer is 10)
If the input is 8 (the anwer is 7)
Similar Threads
Reputation Points: 58
Solved Threads: 1
Posting Whiz in Training
cancer10 is offline Offline
234 posts
since Dec 2004
Mar 8th, 2008
0

Re: nearest number

Hi there,
try something along these lines:
sql Syntax (Toggle Plain Text)
  1. SELECT columnName, ABS(columnName - 9) AS distance
  2. ORDER BY distance LIMIT 1

Could be that ORDER BY won't accept alias distance in which case you'll have to repeat the ABS() code. The trick is in calculating the distance of your number (9) and your column values.

In PHP you then use something like:
$result = mysql_query("SELECT ... ABS(columnName - $myNumber) ...");
list($closestNumber) = mysql_fetch_row($result);

Let me know if this helps.
Petr 'PePa' Pavel
Reputation Points: 27
Solved Threads: 16
Junior Poster
petr.pavel is offline Offline
116 posts
since Mar 2008
Mar 8th, 2008
0

Re: nearest number

what does ABS do?
Reputation Points: 58
Solved Threads: 1
Posting Whiz in Training
cancer10 is offline Offline
234 posts
since Dec 2004
Mar 9th, 2008
0

Re: nearest number

Click to Expand / Collapse  Quote originally posted by cancer10 ...
what does ABS do?
Calculates absolute value: ABS(-10) = 10, ABS(10) = 10
Last edited by petr.pavel; Mar 9th, 2008 at 7:39 am.
Reputation Points: 27
Solved Threads: 16
Junior Poster
petr.pavel is offline Offline
116 posts
since Mar 2008

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in PHP Forum Timeline: When i log on to my site and click a link in it. It is logging out automatically
Next Thread in PHP Forum Timeline: checkbox output





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC