mysql检测表中的重叠日期范围

ruarlubt  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(256)

我有一张表,上面有下列数据。

CREATE TABLE DiscountFormula (
  id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY
, dateFrom date
, dateUntil date
);

INSERT INTO DiscountFormula
  (dateFrom, dateUntil)
VALUES
  ("2020-06-01", "2020-06-10")
, ("2020-06-03", "2020-06-13")
, ("2020-06-25", "2020-06-29")
, ("2020-07-01", "2020-07-01")
, ("2020-07-03", "2020-07-03")
;

小提琴演示

id    dateFrom     dateUtil     
====  ========     ========     
1     2020-06-01   2020-06-10  
2     2020-06-03   2020-06-13  
3     2020-06-25   2020-06-29
4     2020-07-01   2020-07-01
5     2020-07-03   2020-07-03

正如你所看到的 1 以及 2 是日期范围上的重叠。我想创建一个查询来检测表中是否有重叠的日期范围。意思是如果 count > 0 有重叠的数据,所以我可以抛出一个警报消息。我试过了,但似乎不管用。

SELECT * #count(*) as TOTAL
FROM DiscountFormula A
JOIN DiscountFormula B 
ON (A.dateFrom >= B.dateFrom AND A.dateFrom <= B.dateUntil)
OR (A.dateUntil >= B.dateFrom AND A.dateUntil <= B.dateUntil)
xesrikrc

xesrikrc1#

你检测重叠范围的公式有点错误。应该是这样的:

WHERE A.dateFrom < B.dateUntil
  AND A.dateUntil > B.dateFrom
  AND A.id <> B.id

更新的查询:

SELECT COUNT(*)
FROM DiscountFormula A
INNER JOIN DiscountFormula B
    ON A.dateFrom < B.dateUntil AND A.dateUntil > B.dateFrom AND
       A.id <> B.id;
klr1opcd

klr1opcd2#

我建议使用累积最大值:

select count(*)
from (select df.*,
             max(df.dateuntil) over (order by df.datefrom
                                     rows between unbounded preceding and 1 preceding
                                    ) as prev_dateuntil
      from DiscountFormula df
     ) df
where prev_dateuntil > datefrom;

这应该比自连接快得多。如果 count(*)0 那么就没有重叠了。
实际上,我认为 lag() 足以解决此问题:

select count(*)
from (select df.*,
             lag(df.dateuntil) over (order by df.datefrom) as prev_dateuntil
      from DiscountFormula df
     ) df
where prev_dateuntil > datefrom;

相关问题