MySQL Query two different conditions for different count in 1 query

青春壹個敷衍的年華 提交于 2019-12-04 18:09:39

This query should be able to help you. The biggest thing it does is count ALL of the appointments for total and then SUM on an IF status = completed to get you both the total and the completed in the same query.

SELECT
    sc.id,
    COUNT(ap.id) as total,
    SUM(IF(status = 'completed', 1, 0)) as completed
FROM
    com_event_schedules sc
LEFT JOIN
    com_event_schedules_com_appointment_c re
    ON re.com_event_schedules_com_appointmentcom_event_schedules_ida = sc.id
LEFT JOIN
    com_appointment ap
    ON re.com_event_schedules_com_appointmentcom_appointment_idb = ap.id
WHERE
    sc.deleted = 0
GROUP BY
    sc.id

Also, I was noticing you said that it was a One to Many relationship. Relational tables like you have are really for Many to Many. The most efficient way to have a One to Many is to get rid of the com_event_schedules_com_appointment_c table and add a com_event_schedule_id to the com_appointments table.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!