Question

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

Error: unknown column distance

Any idea why this is? and how to fix it?

I appreciate any advice, many thanks in advance!

Was it helpful?

Solution

What database is this? If it's something like MSSQL, you can't use aliases like that elsewhere in a query. You'll have to replicate the whole alias definition:

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

Or wrap the query in another:

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

OTHER TIPS

You can't refer to an alias in an aggregate function. Move the query into a subquery, and then aggregate it in the outer query.

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top