有如下表:
SELECT * FROM subtract_demo; +----+-------+----------+ | id | total | sale_num | +----+-------+----------+ | 1 | 10 | 1 | | 2 | 10 | NULL | +----+-------+----------+ 2 rows in set
使用如下查询语句,查total减去sale_num的值,当sale_num为null时,total-sale_num的值也为null。
SELECT total-sale_num FROM subtract_demo ; +----------------+ | total-sale_num | +----------------+ | 9 | | NULL | +----------------+ 2 rows in set
解决思路:使用IFNULL函数,如下:
SELECT total-IFNULL(sale_num,0) FROM subtract_demo ; +--------------------------+ | total-IFNULL(sale_num,0) | +--------------------------+ | 9 | | 10 | +--------------------------+ 2 rows in set