使用CASE WHEN时,如果在LEFT JOIN中找不到匹配的行,则会忽略列

时间:2016-09-26 07:54:27

标签: php mysql sql

我想获取为医院支付的账单的收集报告。有一张桌子记录了患者支付的预付金额。并非所有患者都预付款。

这是我现在使用的查询

"SELECT SUM(
    CASE 
    WHEN bill_type = 3 THEN b.payable_amount + w.balance
    ELSE 0
 END) AS 'amount'

 FROM bills b 
    LEFT JOIN ip_patients ip on ip.id = b.ip_id
    LEFT JOIN advance w on w.id = (SELECT x.id FROM advance x WHERE x.ip_id = ip.id ORDER BY x.created_at DESC  LIMIT 1)
    WHERE b.doctor_id = '$d->id' AND CAST(b.created_at AS DATE) >= '$date1' AND CAST(b.created_at AS DATE) <= '$date2' AND b.is_cancelled = 0 AND b.is_deleted = 0"

如果患者未支付预付款,则advance表中不会插入任何行。上述查询会发生的情况是,当患者在预先表中没有行时,他的付款被完全忽略(即,bills表中的值未添加到总和中。

1 个答案:

答案 0 :(得分:2)

如果将null添加到非null,则结果为null。例如

MariaDB [sandbox]> set @a = null;
Query OK, 0 rows affected (0.00 sec)

MariaDB [sandbox]> set @b = 100;
Query OK, 0 rows affected (0.00 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> select @a+@b amt;
+------+
| amt  |
+------+
| NULL |
+------+
1 row in set (0.00 sec)

你可以用ifnull来处理这个

set @a = null;
set @b = 100;

select ifnull(@a,0) + ifnull(@b,0) amt;

+-----+
| amt |
+-----+
| 100 |
+-----+
1 row in set (0.00 sec)