拥有一个带有警报的大型数据库,尝试查询是否在任何时间间隔发出警报。尝试了多件事,但遗憾的是没有工作。
这可能是
查询有多个AND,它们按预期工作,直到我查询之间的警报。我只想在vars:to_open和/或:from_open不为空时执行查询的这一部分
Select * from alarm
WHERE
((:from_open :: TIMESTAMPTZ IS NULL OR :to_open :: TIMESTAMPTZ IS NULL
OR (
alarm.time_created <= :to_open :: TIMESTAMPTZ AND
(alarm.time_cleared >= :from_open :: TIMESTAMPTZ OR alarm.time_cleared IS NULL)))
AND ((:from_open :: TIMESTAMPTZ IS NULL AND :to_open :: TIMESTAMPTZ IS NOT NULL)
OR alarm.time_created >= :from_open :: TIMESTAMPTZ
)
AND ((:from_open :: TIMESTAMPTZ IS NULL AND :to_open :: TIMESTAMPTZ IS NOT NULL)
OR
(alarm.time_created >= :from_open :: TIMESTAMPTZ OR
(alarm.time_created <= :from_open AND (alarm.time_cleared >= :from_open
OR alarm.time_cleared IS NULL)))
)
)
答案 0 :(得分:1)
PostgreSQL的范围类型应该就是您所需要的:
SELECT * FROM alarm
WHERE tstzrange(time_created, time_cleared, '()')
&& tstzrange($1, $2, '()');
这很简单,因为tstzrange
的NULL参数会导致间隔在该端无限制。
如果您想要索引来加速查询,请使用
CREATE INDEX ON alarm USING gist (tstzrange(time_created, time_cleared, '()'));
您还可以使用spgist
索引;试验找出哪一个更适合你。