0

这是我正在使用的简单查询(在现实世界中,我正在使用活动记录及其大查询向您展示,所以现在请考虑这个)

SELECT *,(id/* another big query*/) as distance FROM members having distance<=8

如果我运行上面的查询,那么它返回完美的结果总计 5 但我运行这个查询

SELECT count(*),(id/* another big query*/) as distance FROM members having distance<=8

并且计数总是计算我表的所有行,我只想应用条件来获取在上述查询中返回的行数。

我无法删除 having 子句,但我可以将 count 更改为其他内容。

4

3 回答 3

4

您想使用WHERE子句(在聚合之前应用)而不是HAVING子句(聚合之后应用)进行过滤:

SELECT COUNT(*) FROM members WHERE distance <= 8
于 2013-06-12T11:34:16.490 回答
1

你想做这样的事情吗:

select count (*) from
    (
    SELECT *,(id/* another big query/) as distance FROM members having distance<=8
    )
于 2013-06-12T11:32:38.833 回答
0

count 总是计算我表的所有行,我只想将条件与 count 一起应用

count()根据group by子句计算行数:

denis=# select * from test;
 id | test 
----+------
  1 |    1
  2 |    1
  3 |    2
(3 rows)

denis=# select count(*) from test;
 count 
-------
     3
(1 row)

denis=# select count(*), test from test group by test;
 count | test 
-------+------
     2 |    1
     1 |    2
(2 rows)

denis=# select count(*), test from test group by test having count(*) = 2;
 count | test 
-------+------
     2 |    1
(1 row)
于 2013-06-12T11:34:33.683 回答