0

给出这样的查询:

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

4 回答 4

3

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

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

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

于 2013-02-13T23:07:38.080 回答
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;
于 2013-02-13T22:58:14.193 回答
0

尝试:

SELECT 
  id, 
  (SELECT COUNT(*) as mem_count
   FROM members 
   WHERE members.network_id = networks.id)
FROM 
  networks
WHERE mem_count > 2
于 2013-02-13T22:59:34.567 回答
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 相同的问题。

于 2013-02-13T23:07:03.060 回答