0

I need to select all the booking reservations according to date_begin and date_end fields. I have a calendar which only shows 10 days of the selected date calendar.

2017-05-15    -> Date chosen by user
2017-05-10    -> Date begin
2017-05-20    -> Date end

And currently my query is the following:

SELECT *
FROM bookings
WHERE ((date_begin >= '2017-05-10' AND date_begin <= '2017-05-20') OR 
       (date_end >= '2017-05-10' AND date_end <= '2017-05-20'))

Now, what happens is that 90% of my reservations do show on the calendar and works, but there's one if.

If the reservation is longer than 10 days (which is the limit of the calendar) it will only show in the calendar if:

  1. The date_begin exists in the calendar OR
  2. The date_end exists in the calendar

Which means there's a gap in the calendar, between some dates.

2017-05-15    -> Date chosen by user
2017-05-10    -> Date begin
2017-05-20    -> Date end
2017-05-11    -> Date begin reservation
2017-05-27    -> Date end reservation
Shows in calendar? Yes

2017-05-16    -> Date chosen by user
2017-05-11    -> Date begin
2017-05-22    -> Date end
2017-05-11    -> Date begin reservation
2017-05-27    -> Date end reservation
Shows in calendar? Yes

2017-05-17    -> Date chosen by user
2017-05-12    -> Date begin
2017-05-23    -> Date end
2017-05-11    -> Date begin reservation
2017-05-27    -> Date end reservation
Shows in calendar? No!

2017-05-18    -> Date chosen by user
2017-05-13    -> Date begin
2017-05-24    -> Date end
2017-05-11    -> Date begin reservation
2017-05-27    -> Date end reservation
Shows in calendar? No!

2017-05-21    -> Date chosen by user
2017-05-16    -> Date begin
2017-05-27    -> Date end
2017-05-11    -> Date begin reservation
2017-05-27    -> Date end reservation
Shows in calendar? Yes

How can I improve my query?

Linesofcode
  • 5,327
  • 13
  • 62
  • 116

2 Answers2

1

I think you are trying to do this.

SELECT *
FROM bookings
WHERE date_begin <= '2017-05-20' AND date_end >= '2017-05-10'
Vamsi Prabhala
  • 48,685
  • 4
  • 36
  • 58
0

Linesofcode-
This discussion about datetime should work.
(StartDate1 <= EndDate2) and (StartDate2 <= EndDate1)
Thanks to Ian Nelson

Community
  • 1
  • 1
Scott
  • 27
  • 5