Reputation: 63
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.
Upvotes: 1
Views: 221
Reputation: 12804
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
Upvotes: 0
Reputation: 291
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
Upvotes: 1
Reputation: 1984
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
);
Upvotes: 1
Reputation: 70658
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)
Upvotes: 1