MySQL 数据库中有订单表 tbl_test_order01,存储订单数据。其表结构如下所示。
mysql> show full columns from tbl_test_order01;
+------------+-----------+-----------------+------+-----+-------------------+-----------------------------+---------------------------------+----------------------------------------------------------------------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+------------+-----------+-----------------+------+-----+-------------------+-----------------------------+---------------------------------+----------------------------------------------------------------------+
| order_id | char(21) | utf8_general_ci | NO | PRI | | | select,insert,update,references | 订单号 |
| order_at | int(11) | NULL | NO | | 0 | | select,insert,update,references | 订单金额,单位是分 |
| order_st | char(2) | utf8_general_ci | NO | | | | select,insert,update,references | 订单状态 00:成功 01:已退货 02:新建 03:失败 04:已关闭 |
| order_dt | char(8) | utf8_general_ci | NO | | | | select,insert,update,references | 订单日期 yyyymmdd |
| rec_crt_ts | timestamp | NULL | NO | | CURRENT_TIMESTAMP | | select,insert,update,references | 创建时间 |
| rec_upd_ts | timestamp | NULL | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP | select,insert,update,references | 更新时间 |
+------------+-----------+-----------------+------+-----+-------------------+-----------------------------+---------------------------------+----------------------------------------------------------------------+
6 rows in set (0.00 sec)
现在需要统计订单状态为成功的订单总金额,很容易写出如下 SQL 语句。
mysql> SELECT SUM(order_at) AS money FROM tbl_test_order01 WHERE order_st = "00";
+-------+
| money |
+-------+
| NULL |
+-------+
1 row in set (0.00 sec)
这个 SQL 语句表示,当没有符合条件的订单数据时,求和结果返回 NULL。我们希望当没有满足条件的订单时,返回订单总金额为 0。此时,可以借助 COALESCE() 合并函数。具体语法如下所示。
COALESCE(expression 1, expression 2, ....)
COALESCE() 合并函数返回表达式的第一个非空值。如果所有的表达式都为空值,则返回 NULL。
所以结合场景需求,修改上述 SQL 语句如下,即可达到无订单时返回总金额 0。
mysql> SELECT COALESCE(SUM(order_at), 0) AS money FROM tbl_test_order01 WHERE order_st = "00";
+-------+
| money |
+-------+
| 0 |
+-------+
1 row in set (0.00 sec)