我正在尝试从一个表中获取不同的值。当我运行select distinct count(id) from table时,我得到了超过一百万次的计数。然而,如果我运行select count(distinct id) from table,我只有大约300k的计数。这两个查询的区别是什么?
谢谢
发布于 2015-11-08 10:17:32
当你做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采用的不同值的数量。这似乎就是你想要的。
发布于 2015-11-08 09:30:24
如果id是pk,则distinct count(id)的计数将与count(distinct id)返回的行数匹配。
如果id不是pk,但有唯一约束(仅对id,不能与任何其他列组合),则count(distinct id)返回的行数将等于distinct count(id)的计数,与pk的情况相同。
如果id只是另一列,则select count distinct count(id) from table将返回one row,其中包含id列不为NULL的记录的编号,而as select count count(distinct id) from table将返回包含表中所有非NULL唯一id的'one column‘。
在任何情况下,返回的行数或行数都不会超过表中的总行数。
发布于 2015-11-08 09:12:10
第二个select绝对是您想要的,因为它将聚合id(如果使用id=5有10条记录,那么它们都将被算作一条记录),并且select将返回“表中有多少个不同的id”。然而,第一个select会做一些奇怪的事情,我不完全确定它会做什么。
https://stackoverflow.com/questions/33589606
复制相似问题