使用HAVING条件时遇到COUNT问题

时间:2013-06-12 11:30:06

标签: mysql sql database

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

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

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

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

3 个答案:

答案 0 :(得分:4)

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

SELECT COUNT(*) FROM members WHERE distance <= 8

答案 1 :(得分:1)

你想做那样的事情:

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

答案 2 :(得分: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)