我在做什么:
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 中,NULL
与 0
不同。
从概念上讲,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, evenNULL
. An expression that containsNULL
always produces aNULL
value unless otherwise indicated in the documentation for the operators and functions involved in the expression.
i.e.:NULL == 0
results in NULL instead oftrue
. AlsoNULL == NULL
results in NULL, instead of true.- To search for column values that are
NULL
, you cannot use anexpr = NULL
test. To look forNULL
values, you must use theIS NULL
test.- When using
DISTINCT
,GROUP BY
, orORDER BY
, allNULL
values are regarded as equal.- When using
ORDER BY
,NULL
values are presented first, or last if you specifyDESC
to sort in descending order.- For some data types, MySQL handles NULL values specially. If you insert
NULL
into aTIMESTAMP
column, the current date and time is inserted.- If you insert
NULL
into an integer or floating-point column that has theAUTO_INCREMENT
attribute, the next number in the sequence is inserted.- A column that has a
UNIQUE
key defined can still contain multipleNULL
values.
关于mysql - 奇怪的 MySQL AVG() 异常 NULL 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14020924/