How do I query two dates in mysql where the datefrom is in one column and dateto is in the second column of the same table?

时间:2018-03-25 21:04:45

标签: mysql sql database subquery

I have a hotel reservation system MySQL database which has a table 'bookings'. The 'bookings' table includes two columns, datefrom (checkin) and dateto (checkout), their data-types are DATE. I need to query the database to show all bookings between two searchable dates.

The code I have is as follows:

SELECT * FROM bookings WHERE datefrom '2018-06-01' AND '2018-06-07';

This returns any booking where the start date exists between these two dates but I need to adapt the query to include bookings where the date starts before '2018-06-01' but includes the daterange shown in the query above. I understand the DATEDIFF function but I am not sure how/whether I can use that to return a date that, for example starts at '2018-05-23' and finishes '2018-06-02' (within the date range above).

2 个答案:

答案 0 :(得分:0)

I think you want this logic:

SELECT b.*
FROM bookings b
WHERE b.datefrom <= '2018-06-07' AND
      b.datefrom >= '2018-06-01'; 

This gives you any bookings that overlap with that period.

答案 1 :(得分:0)

Following logic checks for overlapping date ranges:

where start1 <= end2 and end2 >= start1

e.g. to find matching rows between '2018-06-01' and '2018-06-07'

WHERE datefrom <= '2018-06-07'
  AND dateto >= '2018-06-01'

Depending on your logic you might need to switch >= to >