Home >Database >Mysql Tutorial >How to Efficiently Retrieve Unmodified Reservations from a Database?
Database Query for Unmodified Reservations
This article addresses the efficient retrieval of unmodified reservations from a database with two tables: reservation
and reservation_log
. A simple WHERE
clause isn't ideal for finding uncancelled reservations; a more sophisticated approach is needed.
Method 1: Exclusion using NOT IN
One method uses negation to exclude cancelled reservations. We identify cancelled reservations in reservation_log
and exclude their IDs from the reservation
table:
<code class="language-sql">SELECT * FROM reservation WHERE id NOT IN ( SELECT reservation_id FROM reservation_log WHERE change_type = 'cancel' );</code>
Method 2: Optimized Query with LEFT JOIN
For better performance, especially with indexed columns, a LEFT JOIN
is recommended:
<code class="language-sql">SELECT r.* FROM reservation r LEFT JOIN reservation_log l ON r.id = l.reservation_id AND l.change_type = 'cancel' WHERE l.id IS NULL;</code>
This LEFT JOIN
returns all rows from the reservation
table. Matching rows from reservation_log
(where a cancellation exists) are included. The WHERE l.id IS NULL
clause filters the results, returning only reservations without a matching cancellation entry in reservation_log
.
Both methods effectively retrieve uncancelled reservations. The LEFT JOIN
approach generally offers superior performance. Choosing the best method depends on database size and indexing.
The above is the detailed content of How to Efficiently Retrieve Unmodified Reservations from a Database?. For more information, please follow other related articles on the PHP Chinese website!