Background
I have a table Deliveries
:
+---------+-------------+---------------+
| courier | pickup_date | delivery_date |
+---------+-------------+---------------+
| Sebby | 2015-05-02 | 2015-05-04 |
| Ian | 2015-05-07 | 2015-05-08 |
| Sebby | 2015-05-12 | 2015-05-16 |
| Bart | 2015-05-18 | 2015-05-21 |
| Ian | 2015-05-27 | 2015-05-29 |
+---------+-------------+---------------+
Visually, The courier's schedule looks like this:
Question
The search criteria is a date range and I have to return which courier is 'available' on that date range. For example, the search criteria is from 2015-05-16 - 2015-05-17
. Looking at the table or the calendar, it's easy to know that only Ian and Bart are available on those dates. How do I do this in MySQL?
What I have tried
I saw this answer so I tried it like so:
SELECT courier FROM Deliveries
WHERE pickup_date > '2015-05-17'
OR delivery_date < '2015-05-16'
This gives me Ian and Bart. But it also includes Sebby. This is because although Sebby's 2015-05-12 - 2015-05-16
overlaps with the search criteria, 2015-05-02 - 2015-05-04
doesn't so it is returned in the query. I need to do something like restrict the query. If the courier's schedule overlaps once, then don't return it in the query. I could do this in the source code but I prefer doing all the filtering in MySQL. Source code will be the last resort.
This popped out on questions that may already have my answer and it seemed similar to my earlier attempt.
This question (and the answer) also talks about my earlier attempt. Everything else that I saw seems related one way or another but does not answer my question.
Am I on the right track? Or my approach to the problem is wrong?
Schema
I will provide the script to create the table to save you the time :)
CREATE TABLE Deliveries (
courier varchar(15),
pickup_date date,
delivery_date date
);
INSERT INTO Deliveries (courier, pickup_date, delivery_date) VALUES
('Sebby', '2015-05-02', '2015-05-04'),
('Ian', '2015-05-07', '2015-05-08'),
('Sebby', '2015-05-12', '2015-05-16'),
('Bart', '2015-05-18', '2015-05-21'),
('Ian', '2015-05-27', '2015-05-29');