tags:

views:

22

answers:

1

Was wondering if someone could help me out a little with this query:

SELECT u1.id,count(DISTINCT u2.userstatus) as TEMPCOLUMN FROM users AS u1
JOIN friendssym ON u1.id = friendssym.user_id
JOIN (SELECT * FROM users) as u2 ON friendssym.friend_id=u2.id
WHERE TEMPCOLUMN=1 
group by u1.id;

I want to only have results where the count (which is renamed) is equal to 1. I get an error with this query:

 ERROR:  column "tempcolumn" does not exist

But the column should exist, right? Can anyone assist? Thanks!

+1  A: 

You can't reference a column alias in the WHERE clause.

  SELECT u1.id,
         COUNT(DISTINCT u2.userstatus) as TEMPCOLUMN 
    FROM USERS AS u1
    JOIN friendssym ON u1.id = friendssym.user_id
    JOIN USERS as u2 ON friendssym.friend_id = u2.id      
GROUP BY u1.id
  HAVING COUNT(DISTINCT u2.userstatus) = 1

In traditional SQL, the earliest you can reference a column alias is the ORDER BY clause. But MySQL and SQL Server allow access in the HAVING and GROUP BY clauses.

OMG Ponies
I was using a column alias because WHERE wouldn't let me use the COUNT directly (it says it can't use aggregates) but the HAVING works perfectly. Thanks for the help!
Airjoe
@Airjoe: Yep, can't use aggregate functions (COUNT, SUM, MIN or MAX) in the WHERE clause outside of a subquery - need to use the HAVING clause for that.
OMG Ponies