Based on http://www.plumislandmedia.net/mysql/haversine-mysql-nearest-loc/
The following SQL Query returns an array of cities nearest to $lat/$lon
pair within a given $radius
. I added another join
-statement (c.)
to display the code3l
-column from table Country
for each city.
Overall this statement takes about 1.2sek due to the amount of 3Mio entries
SELECT population, AccentCity, Country, code3l, name, City, Region,
Latitude, Longitude, distance, id
FROM (
SELECT z.population,z.id,
z.AccentCity,z.Country, z.City, z.Region,
z.Latitude, z.Longitude,
c.name, c.code3l,
p.radius,
p.distance_unit
* DEGREES(ACOS(COS(RADIANS(p.latpoint))
* COS(RADIANS(z.latitude))
* COS(RADIANS(p.longpoint - z.longitude))
+ SIN(RADIANS(p.latpoint))
* SIN(RADIANS(z.latitude)))) AS distance
FROM worldpopulation AS z
JOIN (
SELECT '.$lat.' AS latpoint, '.$lon.' AS longpoint,
'.$radius.' AS radius, 111.045 AS distance_unit
) AS p ON 1=1
JOIN (
SELECT * FROM countries
) AS c ON c.code2l = z.Country
WHERE
z.population IS NOT NULL
AND z.latitude
BETWEEN p.latpoint - (p.radius / p.distance_unit)
AND p.latpoint + (p.radius / p.distance_unit)
AND z.longitude
BETWEEN p.longpoint - (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
AND p.longpoint + (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint))))
) AS d
WHERE distance <= radius
ORDER BY distance ASC';
In addition to that I need to add a some count(*)
-statements to return the amount of passengers in each city. So I tried to add these like this:
SELECT population, AccentCity, Country, code3l, name, City, Region,
Latitude, Longitude, distance,id,
(select count(*) from passengers where city_id = d.id) AS passenger,
(select count(*) from passengers where city_id = d.id AND
start = "'.$icao.'") AS passengerFromHere,
(select count(*) from passengers where city_id = d.id AND
destination = "'.$icao.'") AS passengerToHere
FROM (
SELECT z.population,z.id,
...
but the table named passengers
is growing fast, and with that the overall executing time for the statement
I there a way to Join the heavy passengers
table, having the same result (array of cities with their respective passengers) in a better executing time