繁体   English   中英

select distinct count(id)vs select count(distinct id)

[英]select distinct count(id) vs select count(distinct id)

我正试图从表中获取不同的值。 当我select distinct count(id) from table运行select distinct count(id) from table我得到了超过一百万的计数。 但是,如果我select count(distinct id) from table运行select count(distinct id) from table我只有大约300k计数。 这两个查询的区别是什么?

谢谢

当您select distinct count(id)您基本上在做:

select distinct cnt
from (select count(id) as cnt from t) t;

因为内部查询只返回一行,所以distinct不执行任何操作。 查询计算表中的行数 (更准确地说, id不为null的行数)。

另一方面,当你这样做时:

select count(distinct id)
from t;

然后查询计算id在表中所采用的不同值的数量。 这似乎是你想要的。

第二个选择肯定是你想要的,因为它将聚合id(如果你有10个id = 5的记录,那么它们将被计为一个记录)并且select将返回“表中有多少个不同的id” 。 然而,第一个选择将做一些奇怪的事情,我不完全确定它会做什么。

如果id是pk,则具有distinct count(id)将匹配返回的具有count(distinct id)的行的count(distinct id)

如果id不是pk但具有唯一约束(仅在id上,不与任何其他列组合),则返回带有count(distinct id)的行的count(distinct id)将等于具有distinct count(id) ,如在pk的情况下。

如果id只是另一列, select count distinct count(id) from table将返回one row ,其中id列为NOT NULL的记录,其中select count count(distinct id) from table将返回'one column'with表中的所有非NULL唯一ID。

在任何情况下,返回的计数或行数都不会超过表中行的总数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM