我们知道,SUM()
如果没有匹配的行,该函数将返回NULL,但有时我们希望它返回零而不是NULL。为此,我们可以使用MySQLCOALESCE()
函数,该函数接受两个参数,如果第一个参数为NULL,则返回第二个参数,否则返回第一个参数。为了理解上述概念,请考虑一个“ employee_tbl”表,该表具有以下记录-
mysql> SELECT * FROM employee_tbl; +------+------+------------+--------------------+ | id | name | work_date | daily_typing_pages | +------+------+------------+--------------------+ | 1 | John | 2007-01-24 | 250 | | 2 | Ram | 2007-05-27 | 220 | | 3 | Jack | 2007-05-06 | 170 | | 3 | Jack | 2007-04-06 | 100 | | 4 | Jill | 2007-04-06 | 220 | | 5 | Zara | 2007-06-06 | 300 | | 5 | Zara | 2007-02-06 | 350 | +------+------+------------+--------------------+ 7 rows in set (0.00 sec)
现在,SUM()
当我们使用COALESCE函数SUM()
来查找由'Mohan'键入的页面总数时,MySQL函数返回0 ,该名称不在'Name'列中-
mysql> SELECT COALESCE(SUM(daily_typing_pages),0)AS ‘SUM(daily_typing_pages)’FROM employee_tbl WHERE Name = ‘Mohan’; +-------------------------+ | SUM(daily_typing_pages) | +-------------------------+ | 0 | +-------------------------+ 1 row in set (0.00 sec)