| | |
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 |
.htaccess ajax apache api archive array autocomplete beginner binary broken cakephp checkbox class cms code cron curl database dataentry date display duplicates dynamic echo email emptydisplayvalue error errors execute explodefunction file files folder form forms function functions google href htaccess html image include insert integration ip java javasciptvalidation javascript joomla keywords limit link login loop mail menu mlm mod_rewrite multiple mysql oop oracle paypal pdf php problem query radio random recursion recursive regex remote script search server sessions shot sms soap source space sql subscription syntax system table tutorial tutorials update upload url validation validator variable video web xml youtube





