如何在查询WHERE子句中使用AS名称?

时间:2013-02-13 22:54:19

标签: postgresql postgresql-9.1

给出如下查询:

SELECT 
  id, 
  (SELECT COUNT(*) 
   FROM members 
   WHERE members.network_id = networks.id) AS mem_count
FROM 
  networks
WHERE mem_count > 2

使用此查询,where子句会中断,因为它不知道mem_count是什么...为什么我不能在where子句中使用as var?

由于

4 个答案:

答案 0 :(得分:3)

虽然bernie建议正确回答问题,但您的查询可以简化为:

SELECT
  network_id as id,
  count(*)
FROM
  members
GROUP BY
  network_id 
HAVING
  count(*) > 2

作为额外的奖励,可以更快。

答案 1 :(得分:2)

你已经把这个概念搞定了。你只需要正确的语法。您可以像这样重写,并且可以使您的查询符合ANSI标准:

SELECT 
  id, 
  m.mem_count
FROM 
  networks n 
  JOIN (
    SELECT   m.network_id, 
             COUNT(*) AS mem_count
    FROM     members 
    GROUP BY m.network_id
  ) m 
  ON m.network_id = n.id 
  AND m.mem_count > 2;

答案 2 :(得分:0)

尝试:

SELECT 
  id, 
  (SELECT COUNT(*) as mem_count
   FROM members 
   WHERE members.network_id = networks.id)
FROM 
  networks
WHERE mem_count > 2

答案 3 :(得分:0)

一种方式是。

Select * From (
SELECT 
  id, 
  (SELECT COUNT(*) 
   FROM members 
   WHERE members.network_id = networks.id) AS mem_count
FROM 
  networks)) mem_counts
WHERE mem_count > 2

伯尼建议的加入会更好。基本上你混淆了解析器。当您使用AS来别名列名时,您会遇到group by或order by的同类问题。