创建数据的时候,有时候需要验证时间区间是否唯一。
比如2020年1月1日 ~ 2020年1月10日这个时间区间,创建的数据不可以包含这个区间或在区间范围之内,怎么实现数据查询呢?
开始
数据表结构
表名:test
id | start_at | end_at |
---|---|---|
1 | 2021-05-01 00:00:00 | 2021-05-31 00:00:00 |
想要实现日期区间唯一性会出现四种情况
区间里:
start_at <= '2021-05-03 00:00:00' and end_at >= '2021-05-10 00:00:00'
包含区间:
start_at >= '2021-04-01 00:00:00' and end_at <= '2021-06-03 00:00:00'
区间外(左):
start_at >= '2021-04-03 00:00:00' and start_at <= '2021-05-10 00:00:00'
and end_at >= '2021-05-10 00:00:00'
区间外(右):
start_at <= '2021-05-03 00:00:00' and end_at >= '2021-05-03 00:00:00'
and end_at <= '2021-06-03 00:00:00'
组合:
SELECT
*
FROM
`test`
WHERE
(
(start_at <= '2021-05-01 00:00:00' and end_at >= '2021-05-30 00:00:00') or
(start_at >= '2021-05-01 00:00:00' and start_at <= '2021-05-30 00:00:00'
and end_at >= '2021-05-30 00:00:00') or
(start_at <= '2021-05-01 00:00:00' and end_at >= '2021-05-01 00:00:00'
and end_at <= '2021-05-30 00:00:00') or
(start_at >= '2021-05-01 00:00:00' and end_at <= '2021-05-30 00:00:00')
)
这样就可以查询到是改时间区间内是否存数据。
存在数据:该区间已经存在数据,反则不存在数据