简体   繁体   中英

Select all dates which are not in one of the date ranges

I have a table of time periods. (date ranges). These date ranges can overlap. These date ranges can also be subranges of another data record.

+----+------------+------------+
| id | start_date | end_date   |
+----+------------+------------+
|  1 | 2019-01-01 | 2019-01-31 |
|  2 | 2019-02-01 | 2010-02-28 |
|  3 | 2019-04-01 | 2010-04-30 |
+----+------------+------------+

Then I have a table with invoices with invoice date and invoice number:

+----+--------------+------------+
| id | invoice_date | invoice_no |
+----+--------------+------------+
|  1 | 2019-01-14   | 4534534BG  |
|  2 | 2019-03-01   | 678678AAA  |
|  3 | 2019-04-13   | 123123DDD  |
+----+--------------+------------+

I'm looking for all invoices that are available in one date period.

The goal in this small example would be to find the invoice from March: invoice_no: 678678AAA


My Approach

SELECT *
FROM `invoice`
WHERE (invoice_date BETWEEN '2019-01-01' AND '2019-01-31')

With this solution I would have to mark the found invoices (which provide a result) as "found" and then repeat the query for all other ranges. (Until no open invoices or periods are processed). That would be a lot of queries, because there are a lot of invoices and a lot of time periods. I would like to avoid that.

Is there a trick here how to get the start and end date into the BETWEEN via Select?

To exhibit invoices that do not belong to any of the date ranges defined in the other table, you could use a not exists condition:

select i.*
from invoices i
where not exists (
    select 1
    from periods p
    where i.invoice_date >= p.start_date and i.invoice_date <= p.end_date
)

Another typical solution is to use a left join antipattern, ie:

select i.*
from invoices i
left join periods p 
    on i.invoice_date >= p.start_date and i.invoice_date <= p.end_date
where p.id is null

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