I have table places
place_id | city | country_code | zipcode | lat | lon
Now I want to show places that are within 25 miles of place A. Place A has place_id 1.
SELECT *
FROM `places`
WHERE ( 3959 * acos( cos( radians((SELECT lat FROM places WHERE place_id=1)) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians((SELECT lon FROM places WHERE place_id=1)) ) + sin( radians((SELECT lat FROM places WHERE place_id=1)) ) * sin( radians( lat ) ) ) ) < 25;
This works ok, but there are two the same subqueries
SELECT lat FROM places WHERE place_id=1
Is it possible to optimize this query to not have two the same subqueries but make them into 1?
Your three subqueries will execute for every row in the outer table.
What you can do is convert those subqueries to a single
JOINwhich will only execute once for the entire query in order to find the latitude and longitude ofplace_id 1: