我想在我的数据库中显示诊所名称和我的总收入,其中包含年份和月份的日期条件。
这是我得到的:
SELECT tbl_clinics.clinic_name, COALESCE(SUM(tbl_bill.bill_amt),0) AS clinic_tot FROM tbl_clinics
LEFT OUTER JOIN tbl_check_up ON tbl_clinics.clinic_id = tbl_check_up.clinic_id
LEFT OUTER JOIN tbl_bill ON tbl_check_up.bill_id = tbl_bill.bill_id
WHERE MONTH(tbl_bill.date_billed) = "01"
AND YEAR(tbl_bill.date_billed) = "2018"
AND tbl_clinics.user_id = "2-2017"
GROUP BY tbl_clinics.clinic_name
现在我的查询只返回正确的,如果我有从我的数据库中获取的数据。现在我想要这样的东西:例如我更改日期YEAR(tbl_bill.date_billed) = "2019"
然后我想输出如下:
_________________________________
| Clinic_name | clinic_tot |
---------------------------------
| Clinic 1 | 0 |
---------------------------------
答案 0 :(得分:2)
您的WHERE
子句正在将外部联接转换为内部联接。您需要将除第一个表之外的所有条件的条件移动到ON
子句中:
SELECT c.clinic_name, COALESCE(SUM(b.bill_amt), 0) AS clinic_tot
FROM tbl_clinics c LEFT OUTER JOIN
tbl_check_up cu
ON c.clinic_id = cu.clinic_id LEFT OUTER JOIN
tbl_bill b
ON cu.bill_id = b.bill_id AND
MONTH(b.date_billed) = 1 AND
YEAR(b.date_billed) = 2018
WHERE c.user_id = '2-2017'
GROUP BY c.clinic_name