首页 > 解决方案 > 检查时间范围是否覆盖 Postgres 中的 now()

问题描述

我有一个以office_hours数据类型命名的列timerange,它是通过以下方式定义的:

create type timerange as range (subtype = time)

我想编写一个查询来检查是否now()包含在该时间范围内。我正在寻找的是类似于:

select now() <@ office_hours from users where office_hours is not null;

每当我尝试运行该查询时,我都会收到以下错误消息:

dbeaver 错误信息

查询时间范围是否包含的正确方法是什么now()

标签: sqlpostgresql

解决方案


错误消息已经给出了很好的提示。由于您有一个创建time范围,因此您需要now()在检查遏制之前转换时间。

考虑:

select now()::time <@ office_hours from users where office_hours is not null;

DB Fiddle 上的演示

create type timerange as range (subtype = time);
select now(), now()::time <@ timerange('[20:00,23:00]') contained;

产量:

| now                      | contained |
| ------------------------ | --------- |
| 2019-04-05T20:54:13.113Z | true      |

推荐阅读