Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql func.count(distinct(…)与distinct()的结果不同_Mysql_Sql_Sqlalchemy - Fatal编程技术网

Mysql func.count(distinct(…)与distinct()的结果不同

Mysql func.count(distinct(…)与distinct()的结果不同,mysql,sql,sqlalchemy,Mysql,Sql,Sqlalchemy,我有一个包含空条目的列,例如,此列中的可能值为None、1、2、3 当我使用session.query(func.count(distinct(Entry.col))).scalar()计算列中唯一项的数量时,返回“3” 但是当我使用session.query(Entry.col).distinct().count()执行计数时,返回“4” 为什么后一种方法计算None,而第一种方法不计算空值?MySQL count不计算空值,因此如果您按具有空值的字段计算值,则不会按计数计算行数 DISTIN

我有一个包含空条目的列,例如,此列中的可能值为
None、1、2、3

当我使用
session.query(func.count(distinct(Entry.col))).scalar()计算列中唯一项的数量时,
返回“3”

但是当我使用
session.query(Entry.col).distinct().count()
执行计数时,返回“4”


为什么后一种方法计算
None
,而第一种方法不计算空值?

MySQL count不计算空值,因此如果您按具有空值的字段计算值,则不会按计数计算行数


DISTINCT只返回不同值的数目,因此包含NULL。

在第一种情况下,结果查询如下所示:

SELECT COUNT(DISTINCT(col)) FROM Entry
。。。而且,正如您可能已经知道的,
COUNT
这里实际上不会计算
NULL

但是,在第二种情况下,查询不同,如所示:

现在,只需计算
selectdistinct
query返回的行总数(DISTINCT查询的输出中包含4-NULL)

原因很简单:
query.count
目的是返回如果在没有
count
子句的情况下运行查询将返回的行数。此方法无法控制应使用哪些列进行计数-这就是
func.count(…)
的用途

SELECT count(1) AS count_1 FROM (
    SELECT DISTINCT(col) FROM Entry
) AS anon_1