| | |
nearest number
Please support our PHP advertiser: PostgreSQL or MySQL? Compare and contrast the two most popular open source databases
![]() |
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)
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)
Hi there,
try something along these lines:
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
try something along these lines:
sql Syntax (Toggle Plain Text)
SELECT columnName, ABS(columnName - 9) AS distance 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
![]() |
Similar Threads
- rounding array elements (C++)
- What Certifications do You Have? (IT Professionals' Lounge)
- Rounding floating points (C)
- Stopping a timer (Visual Basic 4 / 5 / 6)
- please help me - extremely clueless :( (C++)
- Seg Fault (C++)
- Create Sound (C++)
Other Threads in the PHP Forum
- Previous Thread: When i log on to my site and click a link in it. It is logging out automatically
- Next Thread: checkbox output
| Thread Tools | Search this Thread |
ajax apache api array beginner binary body broken buttons cakephp checkbox class cms code cron curl database date date/time display dynamic ebooks echo email error file files folder form forms function functions google href htaccess html image include insert integration ip java javascript joomla limit link login loop mail mediawiki menu mlm msqli_multi_query multiple mysql number oop paypal pdf php phpincludeissue phpmyadmin problem query radio random recursion regex remote script search server sessions sms soap source sp space speed sql static subdomain syntax system table tag tutorial update upload url validator variable vbulletin video web websphere white wordpress xml youtube





