在MySQL中嵌套多个SELECT语句的正确方法是什么

时间:2011-08-16 23:02:47

标签: mysql nested subquery

我有以下查询:

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')

我一直收到以下错误:

  

where子句中的未知列距离

2 个答案:

答案 0 :(得分:1)

distance是表的名称,而不是列。

在最后一个长子查询之后加上AS column_name,然后你可以用类似的东西访问它。

WHERE distance.column_name <= 5

答案 1 :(得分:0)

距离似乎是一张桌子。简化查询:

SELECT (... FROM locations) AS distance

也许,你忘了where clase:

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