列不存在?

时间:2010-10-25 23:12:51

标签: sql postgresql

想知道是否有人可以帮助我解决这个问题:

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;

我想只有计数(重命名)等于1的结果。我的查询出错:

 ERROR:  column "tempcolumn" does not exist

但是应该存在,对吧?有人可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:3)

您不能在WHERE子句中引用列别名。

  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

在传统的SQL中,最早可以引用列别名的是ORDER BY子句。但MySQL和SQL Server允许访问HAVINGGROUP BY子句。