Home > Database > Mysql Tutorial > How to Retrieve Uncancelled Reservation Records from a Database?

How to Retrieve Uncancelled Reservation Records from a Database?

Mary-Kate Olsen
Release: 2025-01-23 19:46:44
Original
720 people have browsed it

How to Retrieve Uncancelled Reservation Records from a Database?

Retrieving Uncancelled Reservation Records

Given two tables, reservation and reservation_log, where reservation contains general reservation information and reservation_log tracks changes made to reservations (including cancellations), the task is to extract reservations that have not been cancelled. A simple WHERE clause works effectively for identifying cancelled reservations, but it falls short when searching for uncancelled records.

Fortunately, two approaches can be employed to accomplish this task:

Approach 1: Using NOT IN

This method leverages the NOT IN clause to exclude reservations with matching cancellation records.

SELECT *
FROM reservation
WHERE id NOT IN (
  SELECT reservation_id
  FROM reservation_log
  WHERE change_type = 'cancel'
);
Copy after login

Approach 2: Using LEFT JOIN

An alternative approach is to use a LEFT JOIN operation. The left join retrieves all rows from the reservation table and includes corresponding rows from the reservation_log table if they exist. Rows without matching cancellation records will have NULL values in the reservation_log columns. The WHERE clause can then filter out these rows.

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;
Copy after login

The above is the detailed content of How to Retrieve Uncancelled Reservation Records from a Database?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template