mysql - 奇怪的 MySQL AVG() 异常 NULL 值

标签 mysql sql null

我在做什么:

create table sample (id INT(10) PRIMARY KEY AUTO_INCREMENT,name varchar(255),marks INT(10));

insert into sample (name,marks) VALUES('sam',10);
insert into sample (name,marks) VALUES('sam',20);
insert into sample (name,marks) VALUES('sam',NULL);
insert into sample (name,marks) VALUES('sam',NULL);
insert into sample (name,marks) VALUES('sam',30);

select AVG(marks) from sample GROUP BY(name);

我预期的输出:

AVG = (10+20+30)/5 = 12

MYSQL 的输出:

AVG = (10+20+30)/3 = 20

理想情况下,我想要的是 MYSQL 应该得到 5 行的总和并将其除以 5,但它只除以 3(非 NULL 行)

为什么会发生这种情况,我该怎么做才能获得正确的 AVG,即 60/5? PS:我不能将标记字段设为 NOT NULL,在我的数据库设计中,标记字段允许为 NULL。

谢谢

最佳答案

这是正确的行为,因为 NULL 与数字 0 不同。
这可能会让一些非英语国家的人感到惊讶,因为在许多语言“null”等同于“零”。

在 SQL 中,NULL0 不同。

从概念上讲,NULL指的是“未知值”,因此它与其他值的处理方式不同。这就是为什么 aggregate functions喜欢AVG()忽略 NULL

AVG()仅计算所有“已知”值的平均值。 (= NULL)

来自MySQL docs :

Unless otherwise stated, group functions ignore NULL values.

此外,请阅读 Section "3.3.4.6 Working with NULL Values" 中有关 NULL 的概念的信息MySQL 手册。

为了得到你想要的,你可能会这样做

SELECT AVG(COALESCE(marks, 0))
FROM sample 
GROUP BY name;

COALESCE()如果值为 NULL 则返回用于计算的下一个参数,否则将传递该值。


关于 NULL 的概念有更多常见的误解。这些也在 Section "5.5.3 Problems with NULL" 中进行了解释。手册:

  • In SQL, the NULL value is never true in comparison to any other value, even NULL. An expression that contains NULL always produces a NULL value unless otherwise indicated in the documentation for the operators and functions involved in the expression.

    i.e.: NULL == 0 results in NULL instead of true. Also NULL == NULL results in NULL, instead of true.
  • To search for column values that are NULL, you cannot use an expr = NULL test. To look for NULL values, you must use the IS NULL test.
  • When using DISTINCT, GROUP BY, or ORDER BY, all NULL values are regarded as equal.
  • When using ORDER BY, NULL values are presented first, or last if you specify DESC to sort in descending order.
  • For some data types, MySQL handles NULL values specially. If you insert NULL into a TIMESTAMP column, the current date and time is inserted.
  • If you insert NULL into an integer or floating-point column that has the AUTO_INCREMENT attribute, the next number in the sequence is inserted.
  • A column that has a UNIQUE key defined can still contain multiple NULL values.

关于mysql - 奇怪的 MySQL AVG() 异常 NULL 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14020924/

相关文章:

Java:没有空格的空字符

java - 从 MySQL 数据库中提取 BLOB 多边形?

mysql - MySQL 出现语法错误,但不知道为什么

mysql - Node Sequelize with Mysql order by,最后需要空值

Sql 查询 : co-occurrence of column values

mysql - 查明特定用户是否每天登录

php - 如何从 PHP 7 中的嵌套包含文件中跳出 while 循环?

sql - 根据时间间隔计算分组平均值

c - (char*) 0 是什么意思?

java - 在插入 mysql 表之前检查变量是否为 null