我有 3 个表名为
- com_event_schedules
- com_appointments
- com_event_schedules_com_appointment_c
前两个表之间有关系。
以下是表格的字段
- com_event_schedules -- id -- name -- schedule_date -- start_time -- end_time -- deleted
- com_appointments -- id -- start_time -- end_time -- status
- 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 之间的关系是一对多
我想要的结果 schedule_id,以及 status='completed' 的约会总数
我尝试了以下查询:
SELECT sch.id,COUNT(app.status)
FROM
com_event_schedules sch,
com_appointment app,
com_event_schedules_com_appointment_c rel
WHERE
sch.id=com_event_schedules_com_appointmentcom_event_schedules_ida AND
app.id=rel.com_event_schedules_com_appointmentcom_appointment_idb AND
app.status='completed'
我在结果中期望的是每个计划的 ID,其 COUNT 个约会的状态为“已完成”,如果没有匹配,则 COUNT 应为“0”。
但我在结果中得到的是只有预约 ID 已完成且状态为 COUNT 1 的人。
例如
我有 2 个日程安排,每个日程安排有 3 个约会。其中第一个时间表的一个约会的状态为“已完成”
所以我需要这样的结果
sch_id app.status
1 1
2 0
最佳答案
试试这个:
SELECT
sch.id,
SUM(IF(app.status = 'completed' , 1, 0))
FROM
com_event_schedules sch
INNER JOIN com_event_schedules_com_appointment_c rel
ON rel.com_event_schedules_com_appointmentcom_event_schedules_ida = sch.id
INNER JOIN com_appointment app
ON rel.com_event_schedules_com_appointmentcom_appointment_idb = app.id
GROUP BY
sch.id
HAVING
COUNT(*) > 1
关于php - 在 MySQL 查询中没有得到正确的 COUNT() (修改较早),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16978320/