简体   繁体   中英

Checking row count based on date range against date range

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.

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.

选择该日期范围内的所有行并计算结果:

SELECT count(*) FROM vacation WHERE :input_from BETWEEN date_from AND date_to OR :input_to BETWEEN date_from AND date_to

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM