Understanding SUM(NULL) in MySQL(了解 MySQL 中的 SUM(NULL))
问题描述
通常当 NULL 涉及任何方程时,整个结果将解析为 NULL(例如 SELECT 2 + NULL + 5 返回 NULL)
Usually when NULL is involved in any equation then the whole result resolves into NULL (e.g. SELECT 2 + NULL + 5 returns NULL)
以下情况同样适用:
SELECT SUM(NULL) 返回 NULL.命题#1
当 SUM 用于聚合列并且该列也可以包含 NULL 值时会发生什么?
What happens when SUM is used to aggregate a column and the column can contain NULL values too ?
基于 proposition #1 为什么输出不会导致 NULL.
Based on the proposition #1 why the output doesn't result in NULL.
CREATE TABLE t (age INT NULL);
INSERT INTO t (age) VALUES (15),(20), (NULL), (30), (35);
SELECT
SUM(age)
FROM t;
输出: 100
但我期待 NULL.
在这种情况下,MySQL 是否会默默地跳过那些 NULL 值?
http://sqlfiddle.com/#!9/3f99bb/2
推荐答案
这在 手册
SUM([DISTINCT] expr)
返回 expr 的总和.如果返回集没有行,则 SUM() 返回空值.DISTINCT 关键字可用于仅对不同的值求和expr.
SUM([DISTINCT] expr)
Returns the sum of expr. If the return set has no rows, SUM() returns NULL. The DISTINCT keyword can be used to sum only the distinct values of expr.
如果没有匹配的行,SUM() 返回 NULL.
SUM() returns NULL if there were no matching rows.
还有人说:
本节描述了在其上运行的组(聚合)函数值集.除非另有说明,组函数忽略 NULL价值观.
This section describes group (aggregate) functions that operate on sets of values. Unless otherwise stated, group functions ignore NULL values.
换句话说,SUM 的行为是这样的,因为这就是它的定义方式.
in other words SUM behaves like this because that's the way it's defined to be.
这篇关于了解 MySQL 中的 SUM(NULL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:了解 MySQL 中的 SUM(NULL)
基础教程推荐
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 在多列上分布任意行 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
