SQL: Selecting all from a table, where related table, doesn't have a specified field value

StackOverflow https://stackoverflow.com/questions/23570443

  •  19-07-2023
  •  | 
  •  

Pregunta

I have a database, with a table for venues and bookings. The relationship is 1:M. I want to select all venues, that doesn't have a booking on a specific date. The date field is called booking_date and is present on the bookings table. I'm not the strongest in SQL, but i found the NOT EXISTS, but that seems to give me either no venues or all the venues, depending on whether the date is present in just one of the booking_date fields.

To sum up, what i need is a query that: Select all venues, that doesn't have a booking with a booking_date field = ?.

Venues table: id, int name, string other unimportant fields

Bookings table: id, int customer_id, int venue_id, int booking_date, date

So a venue belongs to a booking. I want all venues, that doesn't have a booking, where the booking_date field is equal to a specified date.

For instance, if i have 5 venues, where one of them has a booking on 2014-06-09, and i supply that date, i want the other 4 venues, that doesn't have a booking on this date.

If anyone is interested, the use for this is to show the venues, that are available on a given date, that the users specify.

¿Fue útil?

Solución

NOT EXISTS sounds exactly what you need:

SELECT *
FROM Venues V
WHERE NOT EXISTS(SELECT 1 FROM bookings
                 WHERE booking_date = 'SomeDate'
                 AND venue_id = V.venue_id)

Otros consejos

I would take care of this in the WHERE (making some assumptions on your tables):

DECLARE @DateCheck date = '2014-05-09';

SELECT
    *
FROM
    Venues
WHERE
    VenueId NOT IN
        (
        SELECT
            VenueId
        FROM
            Bookings
        WHERE
            BookingDate = @DateCheck
        );

Check the below query



    select v.* from
    tbl_venues v
    left join tbl_bookings b on v.VenueID=b.VenueID and b.booking_date ='2014-05-02'
    where b.bookingID is null

where bookingID: the primary column of booking table, venueID: the primary column of venues table

You haven't included exact table structure, but it sounds like this would work.

DECLARE @SomeDate DATE='05/10/2014'

SELECT v.*
FROM Venues v
LEFT JOIN Bookings b on b.VenuesID=v.VenuesID AND CONVERT(DATE,b.Booking_Date)=@SomeDate
WHERE b.Booking_Date IS NULL
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top