MySQL SUM() 函数如何评估列是否也具有 NULL 值?
mysqlmysqli database
假设我们正在计算也具有 NULL 值的列的值的总和,那么 MySQL SUM() 函数将忽略 NULL 值并计算其余值的总和。为了理解这一点,请考虑以下表"employee"的示例,该表具有以下详细信息 −
mysql> Select * from Employee; +----+--------+--------+ | ID | Name | Salary | +----+--------+--------+ | 1 | Gaurav | 50000 | | 2 | Rahul | 20000 | | 3 | Advik | 25000 | | 4 | Aarav | 65000 | | 5 | Ram | 20000 | | 6 | Mohan | 30000 | | 7 | Aryan | NULL | | 8 | Vinay | NULL | +----+--------+--------+ 8 rows in set (0.00 sec)
现在,假设我们想从上表中获取员工的总工资,那么在使用 SUM() 函数计算时,它会忽略 NULL 值。以下查询将生成所需的结果集 −
mysql> Select SUM(Salary) from Employee; +-------------+ | SUM(Salary) | +-------------+ | 210000 | +-------------+ 1 row in set (0.00 sec)
也可以借助以下查询进行验证 −
mysql> Select SUM(Salary) from Employee WHERE Salary IS NOT NULL; +-------------+ | SUM(Salary) | +-------------+ | 210000 | +-------------+ 1 row in set (0.00 sec)