I have wrote the following SQL:
SELECT s.*, (SELECT COUNT(*) FROM orders o WHERE o.schedule_id = s.schedule_id AND o.content_id = s.content_id) as numofbookings
FROM schedules s
WHERE content_id = '{$contentid}'
AND DATEDIFF(`schedule_datetime_from`, now()) > 0
AND (SELECT COUNT(*) FROM orders o WHERE o.schedule_id = s.schedule_id AND o.content_id = s.content_id) < s.schedule_capacity
ORDER BY `s`.`schedule_datetime_from` ASC
Although I am concerned this could be wrote better without querying the orders table twice.
I tried AND numofbookings < s.schedule_capacity although this give error column not found.
1 Answer