列ALIAS在HAVING子句中未被识别,未知列错误

时间:2013-10-29 15:20:23

标签: mysql sql having-clause

SELECT u.*, zz.contid, zz.lng, zz.lat, zz.zip, zz.city, zz.state, (**calc distance**) AS distance
FROM contacts zz
INNER JOIN users u
ON zz.id = u.id
WHERE cond1 = 1, cond2=2, etc..
GROUP BY u.id
HAVING MIN(distance) < 100

错误:未知列距

知道为什么会这样吗?以及如何解决它?

我感谢任何建议,非常感谢!

2 个答案:

答案 0 :(得分:3)

这是什么数据库?如果它类似于MSSQL,则不能在查询中的其他位置使用类似别名。您必须复制整个别名定义:

SELECT big+ugly+calculation AS foo
...
HAVING (big+ugly_calculation) = bar

或者将查询包装在另一个中:

SELECT *
FROM (  SELECT *, big+ugly+calculation AS foo )
WHERE foo = bar

答案 1 :(得分:0)

您无法在聚合函数中引用别名。将查询移动到子查询中,然后在外部查询中聚合它。

SELECT *
FROM (
    SELECT u.*, zz.contid, zz.lng, zz.lat, zz.zip, zz.city, zz.state, (**calc distance**) AS distance
    FROM contacts zz
    INNER JOIN users u
    ON zz.id = u.id
    WHERE cond1 = 1, cond2=2, etc..) subquery
GROUP BY id
HAVING MIN(distance) < 100