奇怪的MySQL AVG()异常NULL值
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了奇怪的MySQL AVG()异常NULL值,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2386字,纯文字阅读大概需要4分钟。
内容图文
![奇怪的MySQL AVG()异常NULL值](/upload/InfoBanner/zyjiaocheng/889/3348a876f3ca433eae70a879e4d5cbc0.jpg)
我在做什么 :
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,在我的db设计中,标记字段允许为NULL.
谢谢
解决方法:
这是正确的行为,因为NULL与数字0不同.
从概念上讲,NULL意味着“缺失的未知值”,并且与其他值的处理方式略有不同.这就是aggregate functions像AVG()忽略NULL的原因.
AVG()仅计算所有已知值的平均值. (=不是NULL =未知)
从MySQL docs开始:
Unless otherwise stated, group functions ignore NULL values.
另外,请阅读MySQL手册Section “3.3.4.6 Working with NULL Values”中关于NULL的概念.
为了得到你想要的东西,你可能会这样做
SELECT AVG(IFNULL(marks, 0)) FROM sample GROUP BY(name);
如果值为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 AVG()异常NULL值全部内容,希望文章能够帮你解决奇怪的MySQL AVG()异常NULL值所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。