Sponsored by NuSphere - PHP Software for PHP Application Developers - On Sale This Week for $100



Go Back   PHP-Editors > Linux, Apache, MySQL > MySQL Help

MySQL Help Post any question relating to MySQL here and hopefully someone can help

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 2008-03-08, 01:42 PM
Junior Member
 
Join Date: Dec 2007
Posts: 8
cancer10 is on a distinguished road
Default nearest number

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)
Reply With Quote
  #2 (permalink)  
Old 2008-03-15, 12:53 AM
Junior Member
 
Join Date: Mar 2008
Posts: 1
tiago is on a distinguished road
Default Re:

Did you already tryed:

table_of_vals
vals
3
6
10
8

if you want the nearest number of 9 (critic case):
<?

$nearest2find = 9;

$query = mysql_query( "select vals from table_of_vals where vals > '".$nearest2find."' or vals < '".$nearest2find."' LIMIT 2" );
while( $row = mysql_fetch_array( $query ) ) {
$nearestnumbers[] = $row['vals'];
}

// At this point we have $nearestnumbers with 2 nearest values
// at our example, this query will return 8 and 10

// then you need to check the absolute distance between the number you had choosed (9)

$first_distance = abs( $nearestnumbers[0] - $nearest2find );
$second_distance = abs( $nearestnumbers[1] - $nearest2find );

if( $first_distance > $second_distance ) {
echo "The nearest number is " . $second_distance;
}
else {
echo "Second distance is greater or equal to first_distance<br />";
echo "The nearest number is " . $first_distance;
}

?>

I didn't tested this script.

[sorry my poor english.

Last edited by tiago; 2008-03-15 at 12:57 AM.
Reply With Quote
Must read Review for Serious PHP Developers


NuSphere PhpED 5.0 : The Staff of php-editors.com recently spent a few days working with NuSphere PhpED 5.0 (a popular PHP IDE) and NuCoder 1.4 (a PHP Encoding Utility), read up on all the details.

Sponsored Links
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT +1. The time now is 08:27 AM.


Powered by vBulletin® Version 3.7.2
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO 3.1.0
© Copyright 2003-2008 www.php-editors.com. The ultimate PHP Editor and PHP IDE site.