查询日期范围postgresql

时间:2018-01-24 13:19:52

标签: sql postgresql date date-range

我有以下postgresql表;

$arg = ['param1' => '1', 'param2' => '2', 'param3' => '3'];

$this->load->library('MyLibrary', $arg, 'custom_name');

如何查询日期范围,以便在2003年6月返回ID 5和6。

2 个答案:

答案 0 :(得分:0)

https://www.postgresql.org/docs/current/static/functions-range.html

使用包含运算符,例如:

postgres=# select '[2000-01-01,2017-01-01)'::daterange @> '2013.01.01'::date;
 ?column?
----------
 t
(1 row)

所以对你而言,它会像是

select * from tbl where "Date" @> '2013.01.01'::date;

答案 1 :(得分:0)

使用包含运算符<@

with my_table(id, dates) as (
values
    (1, '[2017-01-01,2051-01-01)'::daterange),
    (2, '[2017-01-01,2051-01-01)'),
    (3, '[2017-01-01,2051-01-01)'),
    (4, '[2017-01-01,2051-01-01)'),
    (5, '[2000-01-01,2017-01-01)'),
    (6, '[2000-01-01,2017-01-01)'),
    (7, '[2017-01-01,2051-01-01)'),
    (8, '[2017-01-01,2051-01-01)'),
    (9, '[2017-01-01,2051-01-01)'),
    (10, '[2017-01-01,2051-01-01)')
)

select *
from my_table
where '2003-06-01'::date <@ dates;

 id |          dates          
----+-------------------------
  5 | [2000-01-01,2017-01-01)
  6 | [2000-01-01,2017-01-01)
(2 rows)    

了解Range Functions and Operators.

您还可以检查dates:

是否包含日期范围(不是单个日期)
where daterange('2003-01-01', '2003-12-31') <@ dates;

或日期范围是否与dates:重叠

where daterange('2003-01-01', '2003-12-31') && dates;