Best unofficial Apache Server developers community
Username
Forgot password?
Sign in with Twitter account
Sign in with Facebook account

Proper mySQL Statement for Searching Availability Dates

0

41 views

I realize this question has been asked in various forms but I am struggling with its implementation into my application.

Here are my table setup: home: home_id, booking_id, name, address, location, etc booking: booking_id, fromdate, todate

I am trying to build a search that will return the homes availability. So if home "A" is not booked from "4/4/2011 - 4/10/2011" then it will return home "A" as the result.

Thanks for your help.

asked April 4, 2011 12:29 pm CDT
posted via StackOverflow

2 Answers

1
 

It's not going to work unless you start with a normalized database - your current schema makes no sense - presumably a home can have multiple bookings - yet you appear to have booking_id as a foreign key in the home table referencing bookings - this should be the other way around (booking should reference home_id).

Using the correct schema:

SELECT home.*
FROM home h
WHERE NOT EXISTS (
   SELECT 1 FROM booking b
   WHERE b.end_date>$start_time
   AND b.start_date<$end_time
   AND b.home_id=h.home_id
);

or

SELECT home.*
FROM home h 
LEFT JOIN booking b
ON (b.home_id=h.home_id
   AND b.end_date>$start_time
   AND b.start_date<$end_time
)
WHERE b.home_id IS NULL;

With an index on booking (start_time, end_time, home_id) it should be reasonably efficient.

answered April 11, 2011 11:28 am CDT
1
 
SELECT H.home_id, H.name, H.address, H.location
FROM Home H
LEFT JOIN (SELECT booking_id
           FROM booking
           WHERE @fromdate BETWEEN fromdate AND todate
           OR @todate BETWEEN fromdate AND todate) B
ON H.booking_id = B.booking_id
WHERE B.booking_id IS NULL

answered April 11, 2011 11:28 am CDT

Your answer

Join with account you already have


Sign in with Twitter account
Sign in with Facebook account
Sign in with Google Friend Connect

Preview
Similar questions
Compare MySQL dates?
February 8, 2011