0

I have the following query:

SELECT 
locations.*, 
(SELECT COUNT(id) FROM location_scores WHERE location_id = locations.id) AS total_votes, 
(SELECT AVG(location_score) FROM location_scores WHERE location_id = locations.id) AS rating, 
(SELECT COUNT(id) FROM location_views WHERE location_id = locations.id) AS total_views, 
(SELECT COUNT(id) FROM location_procedures WHERE location_id = locations.id) AS total_procedures, 
(SELECT ((ACOS(SIN(32.9063840 * PI() / 180) * SIN(location_latitude * PI() / 180) + COS(32.9063840 * PI() / 180) * COS(location_latitude * PI() / 180) * COS((-96.8590890 - location_longitude) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) FROM locations) AS distance
FROM locations 
WHERE distance <= '5' 
AND locations.id IN ('57', '57', '57', '57', '57', '57', '57', '57', '57', '57', '68', '68', '70', '73', '73', '76', '76', '76', '76', '76', '77', '77')

I keep getting the following error:

Unknown column distance in where clause

1
  • Generally speaking, joins usually perform better than sub-queries, because the query planner can optimize it much better than it can with sub-queries. You might want to consider rewriting this using joins. Commented Aug 16, 2011 at 23:26

2 Answers 2

1

distance is the name of a table, not a column.

Put an AS column_name after that last long subquery, then you would access it with something like.

WHERE distance.column_name <= 5

Sign up to request clarification or add additional context in comments.

2 Comments

No, look at the last subquery. I am selecting a calculation AS distance
You are selecting from a table, the last parenthesis, meaning the table as a whole, is being noted as distance. Even if it contains one value, it is in a table alias-named distance, and you need to grab the value IN that table.
0

The distance seems to be a table. The simplified query:

SELECT (... FROM locations) AS distance

Maybe, you forget the where clase:

SELECT (... FROM locations WHERE location_id = locations.id) AS distance

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.