我有 3 个表名为
- com_event_schedules
- com_appointments
- com_event_schedules_com_appointment_c
它在前两个表之间有关系。
以下是表格的字段
com_event_schedules -- id -- name -- schedule_date -- start_time -- end_time -- 已删除
com_appointments -- id -- start_time -- end_time -- 状态
com_event_schedules_com_appointment_c -- id -- com_event_schedules_com_appointmentcom_event_schedules_ida (schedule_id) -- com_event_schedules_com_appointmentcom_appointment_idb (appointment_id)
com_event_schedule 和 com_appointments 表之间的关系是 1 到 Many
我想要的结果有 schedule_id,以及条件状态='已完成'的约会总数
我尝试了以下查询:
SELECT sch.id,COUNT(app.id) AS total,
(SELECT COUNT(ap.id)
FROM
com_appointment ap,
com_event_schedules sc,
com_event_schedules_com_appointment_c re
WHERE
re.com_event_schedules_com_appointmentcom_event_schedules_ida=sc.id AND
ap.id=re.com_event_schedules_com_appointmentcom_appointment_idb AND
sc.deleted=0 AND
ap.status='completed') AS completed
FROM
com_event_schedules sch,
com_appointment app,
com_event_schedules_com_appointment_c rel
WHERE
rel.com_event_schedules_com_appointmentcom_event_schedules_ida=sch.id AND
app.id=rel.com_event_schedules_com_appointmentcom_appointment_idb AND
sch.deleted=0 GROUP BY sch.id
使用此查询我得到准确的总计数,但完成的计数不如预期。它为每个时间表显示 1。然而,数据库中只有 1 个预约已完成,其他预约仍在等待中。
查询有问题吗??我在后端有 SugarCRM。不能使用小提琴导致关系和字段太乱。