0
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!

4
  • 1
    Since MIN() is an aggregate function, its argument must be a column value, not an alias. Commented Oct 29, 2013 at 15:23
  • I don't see what this has to do with PHP or sessions. Please correct the tags. Commented Oct 29, 2013 at 15:25
  • I added the sql tag. It would be helpful if you also added the specific DBMS you're using. Commented Oct 29, 2013 at 15:26
  • Sorry about the tags, I corrected that. Commented Oct 29, 2013 at 15:35

2 Answers 2

3

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 
Sign up to request clarification or add additional context in comments.

4 Comments

The difference between HAVING versus WHERE is that HAVING can refer to aliases. However, it can't refer to an aggregate of an alias.
But that's the point of HAVING, to check aggregates. Otherwise it would be in your where clause.
I tried using distance in where clause and removing having, still getting unknown column error
Did you read my first line? You can't use aliases like that elsewhere in the same query. changing it from 'having' to 'where' won't change the fact that you're trying to use an alias within the same query.
1

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.