简体   繁体   English

SQL-无效的列名

[英]SQL - invalid column name

I have the following query: 我有以下查询:

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

This stopped working when I added the part GROUP BY v.outcode HAVING SUM(distance)>100 当我添加零件GROUP BY v.outcode HAVING SUM(distance)>100时,此操作停止工作

It says Server was unable to process request. 它说服务器无法处理请求。 ---> Invalid column name 'distance' . --->无效的列名'distance'

Any ideas why? 有什么想法吗?

distance is a column alias and you can't refer to a column alias in a HAVING clause. distance是列别名,您不能在HAVING子句中引用列别名。 But you can use aliases in an ORDER BY . 但是您可以在ORDER BY使用别名。

Try changing to: 尝试更改为:

HAVING SUM(6 * o.lat)>100 
ORDER BY distance

The "alias" distance only just defined within the query as "6*o.lat" can not yet be used within the query but only afterwards. 仅在查询中仅定义为“ 6 * o.lat”的“别名”距离尚未在查询中使用,只能在之后使用。

alternative solution is 替代解决方案是

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

Use ORDER BY 6 * o.lat . 使用ORDER BY 6 * o.lat You cannot use the clause AS for an ORDER BY 您不能将AS子句用于ORDER BY

I believe you need to use SUM(6* o.lat), because not every database server can use aliased columns in having clause (It has to do with query planning, parsing etc.). 我相信您需要使用SUM(6 * o.lat),因为不是每个数据库服务器都可以在Haves子句中使用别名列(这与查询计划,解析等有关)。 Depends on what DB you use. 取决于您使用的数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM