此 mySQL 查询存在问题:(使用带有 AS 子句的 WHERE)
我的 SQL 查询工作正常,直到我尝试添加 'WHERE distance << 10' 和“计算块 AS 距离”分别位于第 4 行和第 10 行。知道我该如何修复它吗?谢谢!
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将公式放入 WHERE 子句中,而不是使用别名距离。在 SQL 查询中,WHERE 子句在 SELECT 语句之前计算,因此别名(在本例中为
distance
)尚不存在。您的 SQL 语句如下所示:通过名称引用
distance
的唯一方法是将您的语句包装起来,并将其放入新 SELECT 语句中的表中。例如: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
distance
by name would be to wrap your statement and make it into a table in a new SELECT statement. For example: