0
votes

I have a database of addresses and I'm setting up a map search option on my website. The database has data such as address, price, numberOfBedrooms, numberOfBathrooms, Latitude, Longitude, etc. A user has the option to search by City and Price. Once a user clicks the search button I construct my sql query and return the results. How can I get the latitude and longitude range in 4 separate variables (ie. Highest Lat, Lowest Lat, Highest Long, and Lowest Long) in order to set the boundaries for google maps?

mysql query example:

SELECT * FROM table WHERE City = "city" AND Price BETWEEN "100000" AND "200000"

Let's say it returned 50 results. Would it be more efficient to do more sql queries to find the min and max lat/lng coordinates, or is there a way to loop through the results to find the min/max lat/lng using only one query that would be quicker?

EDIT: I should point out that I also need it to return all the other columns as well as the highest and lowest lat/lng

1
Are lat and lng in two columns, or one comma-separated latlng string? - lufc
lat and lng are in two separate columns - user2588317
Are you using MySQL 8? - lufc
I'm using MySQL 5.6 - user2588317

1 Answers

1
votes

You could do this in MySQL < 8 like this:

SELECT id, price, lat, lng, maxlat, minlat, maxlng, minlng
FROM places
FULL  JOIN
    (SELECT MAX(lat) maxlat, MIN(lat) minlat, MAX(lng) maxlng, MIN(lng)          
            minlng FROM places) a
WHERE price BETWEEN 100 AND 250

This would set the bounds to the full dataset. If you wanted the bounds to be within the result set you would need to copy the WHERE conditions into the subquery. This requires two scans of the table so you need to determine if this is efficient in your case.

With MySQL version 8 you can define the query once and scan the results as follows:

WITH myQuery AS
(SELECT id, price, lat, lng
FROM places
WHERE price BETWEEN 100 AND 250)

SELECT * FROM myQuery FULL JOIN (SELECT Max(lat), MIN(lat), MAX(lng), MIN(lng) FROM myQuery) a

This is probably the most efficient SQL-based solution.

Otherwise you can do:

$result = mysqli_query($connection,"SELECT id, price, lat, lng
FROM places
WHERE price BETWEEN 100 AND 250");

while ($result = mysqli_fetch_assoc($result)) {
     $maxLng = (!isset($maxLng) || $result['lng'] > $maxLng) ? $result['lng'] : $maxLng;
     //etc..
}

This would be the most efficient if you are already looping over your results as part of your existing code, which I suspect you are.

Fiddle here: https://www.db-fiddle.com/f/67ff6UpKC2YT5yFudrZZH3/0