什么时候应该使用 GROUP BY?

When should I use GROUP BY?

根据文档:

Aggregate functions often need an added GROUP BY statement.

嗯,我有一个包含聚合函数的查询:

select col1, count(col2)
from table
where col1 = 'anything'
group by col1;

现在,我的问题是:上面查询中的group by是有用还是没用?因为有 where 子句,我认为它不再需要 group by 了。我错了吗?

如果没有 Group By 语句,count 的输出将始终为 1,并且每次出现都会得到一条记录。

Group by 连同您的情况下的 WHERE,匹配 col1 = "anything" 的所有记录,将它们分组在一起,然后计算分组的记录数量。

这个怎么样:

select count(*) as theCount
from table
where col1 = 'anything';

如果我没看错茶叶的话。很高兴删除答案(我们每天收到 5 个 :))

架构

create table t9
(   id int auto_increment primary key,
    col1 varchar(10) not null,
    col2 varchar(10) not null
);

insert t9 (col1,col2) values ('a','b'),('a','b'),('a','c'),('b','z');

几个问题

select count(*) as theCount 
from t9 
where col1 = 'a';
+----------+
| theCount |
+----------+
|        3 |
+----------+

select count(col2) as theCount 
from t9 
where col1 = 'a';
+----------+
| theCount |
+----------+
|        3 |
+----------+

select count(distinct col2) as theCount 
from t9 
where col1 = 'a';
+----------+
| theCount |
+----------+
|        2 |
+----------+

select col1,count(*) as theCount 
from t9 
group by col1 
order by col1;
+------+----------+
| col1 | theCount |
+------+----------+
| a    |        3 |
| b    |        1 |
+------+----------+

select col1,count(*) as theCount 
from t9 
where col1='a' 
group by col1 
order by col1;
+------+----------+
| col1 | theCount |
+------+----------+
| a    |        3 |
+------+----------+

Group by 与聚合函数一起使用,例如计数。

在您的示例中不需要分组依据,因为您将结果限制为一个值,因此您的 select 等于:

select count(*)
from table
where col1 = 'anything';

但是,如果您删除 where 过滤器:

select col1, count(col2)
from table
group by col1;

您将看到有多少行具有不同的 col1 值。所以它会 运行 你的第一个 select 每个 col1 值。