My SQL query is working fine, until I try to add a ‘WHERE distance < 10’ and ‘chunk-of-calculation AS distance’ on 4th and 10th line respectively. Any idea how I can fix it? Thanks!
Unknown column 'distance' in 'where clause'
SELECT SQL_CALC_FOUND_ROWS places.*, category.*,
COUNT(places_reviews.place_id) AS num_reviews,
(places_popularity.rating_1 + 2*places_popularity.rating_2 + 3*places_popularity.rating_3 + 4*places_popularity.rating_4 + 5*places_popularity.rating_5)/(places_popularity.rating_1 + places_popularity.rating_2 + places_popularity.rating_3 + places_popularity.rating_4 + places_popularity.rating_5) AS average_rating,
6371 * acos( cos( radians(places.lat) ) * cos( radians( 1.29315 ) ) * cos( radians( 103.827164 ) - radians(places.lng) ) + sin( radians(places.lat) ) * sin( radians( 1.29315 ) ) ) AS distance
FROM (places)
JOIN category
ON places.category_id = category.category_id
LEFT JOIN places_reviews ON places_reviews.place_id = places.id
LEFT JOIN places_popularity ON places_popularity.place_id = places.id
WHERE `places`.`category_id` = 1 AND `distance` < 5 AND places.name LIKE '%%' GROUP
BY places.id
ORDER BY id desc
LIMIT 5
You will need to put the formula in your WHERE clause instead of using the alias distance. In a SQL query, the WHERE clause is evaluated before the SELECT statement so the alias (in this case
distance) does not exist yet. Here is what your SQL statement will look like:The only way you could refer to
distanceby name would be to wrap your statement and make it into a table in a new SELECT statement. For example: