用于表示此SQL查询的更好/替代方法

时间:2012-05-03 07:43:51

标签: mysql

写出以下查询的更好/更有效的方法是什么?

当前的SQL查询可以正常工作,但随着数据库变大,我担心处理时间。

SELECT *
FROM room
JOIN catering ON room.room_id = catering.room_id
WHERE capacity BETWEEN '$minCapacity' AND '$maxCapacity' 
AND room.room_id NOT IN 
    (SELECT room_id
    FROM room_booking
    WHERE date_booked = '$us_date')
AND catering.grade = '$grade' ORDER BY room.capacity

1 个答案:

答案 0 :(得分:1)

您可以将NOT IN更改为NOT EXISTS。如果有大量数据可以提高性能:

SELECT *
FROM room
JOIN catering ON room.room_id = catering.room_id
WHERE capacity BETWEEN '$minCapacity' AND '$maxCapacity' 
AND NOT EXISTS
(
    SELECT
        NULL
    FROM
        room_booking
    WHERE
        date_booked = '$us_date'
        AND room.room_id=room_booking.room_id
)
AND catering.grade = '$grade' 
ORDER BY room.capacity