Postgres:选择跨越午夜的时间间隔

时间:2017-11-07 21:38:29

标签: sql postgresql

我有下表:

 id |    time     
----+-------------
  1 | 21:00:00+01
  2 | 22:00:00+01
  3 | 23:00:00+01

id的类型为整数,时间为time with timezone。我想选择落在指定时间间隔内的所有行,例如,

select *
from times
where time >= time '22:30' - interval '60 minutes' and time <= time '22:30' + interval '60 minutes';

但是,如果intervall延伸到午夜,即当我选择23:30作为时间参数时,我会得到一个空的结果集。

有没有办法告诉postgress忽略跨越午夜的会议记录?

1 个答案:

答案 0 :(得分:1)

您可以使用此逻辑:

select *
from times t cross join
     (values ('22:30'::time - interval '60 minutes', '22:30'::time + interval '60 minutes') 
     ) v(fromt, tot)   
where (fromt <= tot and time >= fromt and time <= tot) or
      (fromt > tot and (time >= fromt or time <= tot))