MySQL在where子句中使用内部查询

时间:2011-12-19 21:30:03

标签: mysql

我写了以下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

虽然我担心这可以更好地编写,而无需两次查询订单表。 我尝试了AND numofbookings < s.schedule_capacity虽然没有找到错误列。

1 个答案:

答案 0 :(得分:4)

SELECT s.*, COUNT(o.schedule_id) AS numofbookings
    FROM schedules s
        LEFT JOIN orders o
            ON s.schedule_id = o.schedule_id
                AND s.content_id = o.content_id
    WHERE s.content_id = '{$contentid}'
        AND DATEDIFF(s.schedule_datetime_from, now()) > 0
    GROUP BY s.schedule_id, s.content_id
    HAVING COUNT(o.schedule_id) < s.schedule_capacity
    ORDER BY s.schedule_datetime_from ASC