Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Searching negative longitude values with BETWEEN

I have found many similar posts and even tried to find out how to handle negative values within MySQL, but to no avail.

I have a site that I'm using Google Maps on and as a performance enhancement I'm limiting the markers that are drawn on the map to those that are within the map boundaries.

I would like to develop a query that will work with positive or negative latitude and longitude values.

For the database:

latitude FLOAT( 10, 6 )
longitude FLOAT( 10, 6 )

The query:

SELECT *
FROM `table` 
WHERE `latitude` BETWEEN 47.926930 AND 47.929806 
AND `longitude` BETWEEN -97.077303 AND -97.083997

If I drop the BETWEEN clause for longitude I get results, albeit incorrect with no longitude constraint.

I have tried this:

AND -`longitude` BETWEEN ABS( -97.077303 ) AND ABS( -97.083997 )

Which does work, but only for negative longitude values.

Do I need to check longitude if its negative?

like image 454
hungerstar Avatar asked Apr 02 '12 18:04

hungerstar


3 Answers

You can also use the greatest() and least() functions, so you don't have to worry about the parameters. For example:

SELECT * FROM table
WHERE latitude BETWEEN least(@lat1, @lat2) AND greatest(@lat1, @lat2)
AND  longitude BETWEEN least(@lon1, @lon2) AND greatest(@lon1, @lon2)
like image 163
Mosty Mostacho Avatar answered Nov 15 '22 04:11

Mosty Mostacho


between expects the format to be somefield BETWEEN lowervalue AND highervalue. Your negative longitudes have the higher/lower values switched. It should be

AND longitude BETWEEN -97.083997 AND -97.077303

negative 97.08 is actually lower than negative 97.07

like image 39
Marc B Avatar answered Nov 15 '22 03:11

Marc B


Do check how negative numbers appear on a number line. :)

SELECT *
FROM `table` 
WHERE `latitude` BETWEEN 47.926930 AND 47.929806 
  AND `longitude` BETWEEN -97.083997 AND -97.077303 
like image 35
hjpotter92 Avatar answered Nov 15 '22 05:11

hjpotter92