我有三个表,我曾经离开外部联接查看我的所有诊所名称,包括我需要的数据的总和和计数,我在这里有下面的表截图:
现在,我的查询是这样的:
SELECT
tbl_clinics.clinic_name,
COALESCE(COUNT(tbl_check_up.check_up_id),0) AS totalpatient,
COALESCE(SUM(tbl_bill.bill_amt),0) AS totalearn
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_bill.bill_id = tbl_check_up.bill_id
WHERE tbl_clinics.user_id = 102
我的查询输出是:
问题: 现在,我的问题是我想通过显示零到零值来显示我的其他诊所。在我的数据中,我有3个诊所,其user_id = 102,但为什么只有诊所1显示? 。我想要一些如下所示的输出,其中显示tbl_check_up中没有值,其诊所ID为2和3与账单相同。
+---------------+---------------+------------+
| Clinic Name | Total Patient | Total Earn |
+---------------+---------------+------------+
| Clinic 1 | 4 | 800.00 |
+---------------+---------------+------------+
| Clinic 2 | 0 | 0 |
+---------------+---------------+------------+
| Clinic 3 | 0 | 0 |
+---------------+---------------+------------+
答案 0 :(得分:2)
这是您的查询(COALESCE()
不需要COUNT()
):
SELECT c.clinic_name,
COUNT(cu.check_up_id) AS totalpatient,
COALESCE(SUM(b.bill_amt), 0) AS totalearn
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 b.bill_id = cu.bill_id
WHERE c.user_id = 102
GROUP BY c.clinic_name;
我认为你只需要GROUP BY
。