使用overlaps 运算符:
select count(*) = 0 as allow_booking
from "table"
where (from_date, to_date) overlaps (date '2017-04-20', date '2017-04-25');
这也将处理未完全在测试范围内的预订。
如果允许预订,查询将返回true,否则返回false。
例子:
create table bookings
(
id serial,
from_date date,
to_date date
);
insert into bookings
(from_date, to_date)
values
(date '2017-04-20', date '2017-04-20'),
(date '2017-04-20', date '2017-04-24'),
(date '2017-04-26', date '2017-04-29');
那么下面
select *
from bookings
where (from_date, to_date) overlaps (date '2017-04-18', date '2017-04-19');
不会返回任何内容,因此,count(*) = 0 返回true
以下查询:
select *
from bookings
where (from_date, to_date) overlaps (date '2017-04-20', date '2017-04-25');
返回:
id | from_date | to_date
---+------------+-----------
1 | 2017-04-20 | 2017-04-20
2 | 2017-04-20 | 2017-04-24
所以count(*) = 0 返回false
还有查询:
select *
from bookings
where (from_date, to_date) overlaps (date '2017-04-27', date '2017-04-28');
将返回:
id | from_date | to_date
---+------------+-----------
3 | 2017-04-26 | 2017-04-29
而count(*) = 0 也是错误的。