| | |
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
Views: 664 | Replies: 3
| Thread Tools | Search this Thread |
Tag cloud for PHP
.htaccess access ajax apache api array beginner binary broken cakephp checkbox class cms code cron curl database dataentry date directory display download dynamic echo email error file files firstoptioninphpdroplist folder form forms freelancing function functions google href htaccess html image include insert integration ip java javascript joomla jquery limit link login loop mail menu methods mlm mod_rewrite multiple mysql oop parse paypal pdf php problem query radio random recursion regex remote script search select server sessions sms soap source space speed sql structure syntax system table tutorial tutorials update updates upload url validation validator variable video web white xml youtube





