我有以下查询:
SELECT o.outcode AS lead_postcode, v.outcode AS venue_postcode, 6 * o.lat AS distance
FROM venue_postcodes v, uk_postcodes o
WHERE o.outcode = 'CF3'
GROUP BY v.outcode
HAVING SUM(distance)>100
ORDER BY distance
当我添加部件GROUP BY v.outcode HAVING SUM(distance)>100
它说服务器无法处理请求。 --->列名称“距离”无效。
任何想法为什么?
答案 0 :(得分:6)
distance
是列别名,您无法引用HAVING
子句中的列别名。但您可以在ORDER BY
中使用别名。
尝试更改为:
HAVING SUM(6 * o.lat)>100
ORDER BY distance
答案 1 :(得分:2)
仅在查询中定义为“6 * o.lat”的“别名”距离尚未在查询中使用,但仅在之后使用。
替代解决方案是
SELECT i.*
FROM (
SELECT o.outcode AS lead_postcode, v.outcode AS venue_postcode, 6 * o.lat AS distance
FROM venue_postcodes v, uk_postcodes o
WHERE o.outcode = 'CF3'
) i
GROUP BY i.outcode
HAVING SUM(i.distance)>100 ORDER BY i.distance
答案 2 :(得分:0)
使用ORDER BY 6 * o.lat
。您不能对ORDER BY
答案 3 :(得分:0)
我相信你需要使用SUM(6 * o.lat),因为不是每个数据库服务器都可以在having子句中使用别名列(它与查询规划,解析等有关)。取决于你使用的数据库。