我已经读过你不能在WHERE子句中使用ALIAS,但我仍然没有一个很好的替代解决方案来实现我在下面尝试做的事情。我的DISTANCE计算可以做什么,以便它在WHERE子句中可用?
SELECT n.nid AS nid, location.name AS location_name, (6371.0 * ACOS(SIN((location.latitude * RADIANS(1))) * SIN((28.755925 * RADIANS(1))) + COS((location.latitude * RADIANS(1))) * COS((28.755925 * RADIANS(1))) * COS((location.longitude * RADIANS(1)) - (-81.346395 * RADIANS(1))))) AS distance
FROM
node n
LEFT JOIN location_instance ON n.vid = location_instance.vid
LEFT JOIN location ON location_instance.lid = location.lid
WHERE (( (n.status = '1') AND (n.type IN ('locations')) AND (distance <= 100) ))
ORDER BY distance
LIMIT 10
答案 0 :(得分:4)
MySQL扩展了HAVING
子句的使用,可用于此目的。如果查询不是聚合查询,那么HAVING
仍会进行过滤 - 但它允许使用别名。
所以,你可以写:
SELECT n.nid AS nid, l.name AS l, (6371.0 * ACOS(SIN((l.latitude * RADIANS(1))) * SIN((28.755925 * RADIANS(1))) + COS((l.latitude * RADIANS(1))) * COS((28.755925 * RADIANS(1))) * COS((l.longitude * RADIANS(1)) - (-81.346395 * RADIANS(1))))) AS distance
FROM node n LEFT JOIn
location_instance li
ON n.vid = li.vid LEFT JOIN
location l
ON li.lid = l.lid
WHERE n.status = 1 AND n.type IN ('locations')
HAVING distance <= 100
ORDER BY distance
LIMIT 10;
注意:
status
是一个似乎可能的数字,那么您应该与数字进行比较,而不是字符串。status
和type
可以放在HAVING
条款中,但我怀疑它们在WHERE
中更好(我怀疑HAVING
会影响UNT*106*0001~
优化选择)。