了解 MySQL 中的 SUM(NULL) [英] Understanding SUM(NULL) in MySQL

查看:27
本文介绍了了解 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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆