Reputation: 63
I'd like to ask you, if there is any way in mysql to do this. I know it can be done by cycle, but feeling like there has to be a better way.
I have table vacation
id | date_from | date_to
1 2017-02-16 2017-02-19
2 2017-02-18 2017-02-21
3 2017-02-12 2017-02-19
4 2017-02-19 2017-02-21
The thing is, that user picks the date range he wants to reserve, like 2017-02-14 to 2017-02-24 and I have to check whether he can still request it, because only 4 people can request vacation simultaneously.
So I need query which will check whether in user selected range (for example 2017-02-14 to 2017-02-24) are for any day 4 or more rows.
Thanks in advance for your answers.
Upvotes: 0
Views: 48
Reputation: 4121
Select all rows in that date range and count the results:
SELECT count(*) FROM vacation WHERE :input_from BETWEEN date_from AND date_to OR :input_to BETWEEN date_from AND date_to
Upvotes: 0
Reputation: 1271121
You can do this for any day:
select count(*)
from vacation v
where '2017-02-14' between date_from and date_to;
You can extend this to a range, by specifying each day:
select dte, count(v.id)
from (select date('2017-02-14') as dte union all
select date('2017-02-15') as dte union all
select date('2017-02-16') as dte union all
select date('2017-02-17') as dte union all
select date('2017-02-18') as dte union all
. . .
) d left join
vacation v
on d.dte between date_from and date_to
group by d.dte
having count(*) > 4;
It might be simpler to loop through on the application side. Or, to use a calendar table if you have one.
Upvotes: 1