简体   繁体   中英

I need Mysql Query to Find available dates for the selected month and year excluding the dates taken from a table


Could you please help.
I need to show available dates with in the range of dates Taken from table

I have a booking table. It contains mStartdate and end date

Read the table and and show all available dates excluding the dates taken from table for the selected month and year.

booking Table
| Id | StartDate | EndDate |
| 1 |2020-03-05 | 2020-03-05|
| 2 |2020-03-10 | 2020-03-11|
| 3 |2020-03-12 | 2020-03-14|
| 3 |2020-03-16 | 2020-03-18|

What I need is all the available dates for the month 03 ie March. example

2020-03-01 t0 2020-03-04 is available
2020-03-06 t0 2020-03-09 is available
2020-03-15 t0 2020-03-15 is available
2020-03-19 t0 2020-03-31 is available

I want to make it little more clear that I want
to read date from booking table for the Month March. Then Create a list of available dates Like

2020-03-01
2020-03-02
2020-03-03
2020-03-04
2020-03-06
2020-03-07
2020-03-08
2020-03-09
2020-03-15
2020-03-19
to
2020-03-31

Thank you friends. Please help me.

In MySQL 8.0, you could use a recursive common table expression to generate the list of dates of the month, then filter it with the date ranges defined in the table:

with recursive cte as (
    select '2020-03-01' dt
    union all select dt + interval 1 day 
    from cte
    where dt + interval 1 day < '2020-04-01'
)
select dt
from cte c
where not exists (select 1 from mytable t where c.dt between t.start_date and t.end_date)
order by dt

In earlier versions, one solution involves a table of numbers; here is a solution with a derived table

select '2020-03-01' + interval x.n day dt
from (select 0 n union all select 2 ... union all select 30) x
where not exists (
    select 1
    from mytable t
    where '2020-03-01' + interval x.n day between t.start_date and t.end_date
)
order by dt

You can using UNION for getting result from two columns. I just write query for one column. Same method apply for another column. Methid 1 Using CAST() method with MySql BETWEEN approach

SELECT *
FROM tableName
WHERE StartDate BETWEEN CAST('2014-02-01' AS DATE) AND CAST('2014-02-28' AS DATE);

Method 2 Using CAST() method without MySql BETWEEN approach

SELECT *
FROM tableName
WHERE StartDate >= CAST('2014-02-01' AS DATE)
AND StartDate <= CAST('2014-02-28' AS DATE);

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