Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PostgreSQL 9.3-元素包含在vs.BETWEEN中_Sql_Postgresql_Postgresql 9.3 - Fatal编程技术网

PostgreSQL 9.3-元素包含在vs.BETWEEN中

PostgreSQL 9.3-元素包含在vs.BETWEEN中,sql,postgresql,postgresql-9.3,Sql,Postgresql,Postgresql 9.3,我有一个30米长的简单表格 CREATE TABLE "Foo"."Bar" ( "BarID" BIGSERIAL PRIMARY KEY, "DateTime" TIMESTAMP NOT NULL, "Bar" TEXT NOT NULL ); 。。。一个简单的索引: CREATE INDEX ON "Foo"."Bar"("DateTime"); 。。。还有一个简单的问题: 在2015年的第一个小时,哪些BarID值具有DateTime值 所以我提出了这个问题

我有一个30米长的简单表格

CREATE TABLE "Foo"."Bar" (
    "BarID" BIGSERIAL PRIMARY KEY,
    "DateTime" TIMESTAMP NOT NULL,
    "Bar" TEXT NOT NULL
);
。。。一个简单的索引:

CREATE INDEX ON "Foo"."Bar"("DateTime");
。。。还有一个简单的问题:

在2015年的第一个小时,哪些BarID值具有DateTime值

所以我提出了这个问题1:

SELECT
    "Bar"."BarID"
FROM
    "Foo"."Bar"
WHERE
    "Bar"."DateTime" <@ TSRANGE('2015-01-01 00:00:00', '2015-01-01 01:00:00');
后果 查询1使用序列扫描在60秒内运行

查询2使用索引扫描在0.02秒内运行

我尝试使用GiST制作另一个索引,但没有任何改进


给出了什么?

范围表达式是可搜索的。您只需要一个范围表达式可以使用的索引。在timestamp类型的列上有一个B树索引和一个GiST索引。时间戳范围表达式不能利用这两个索引中的任何一个

在时间戳范围表达式上创建GiST索引,并更新统计信息

create index on "Foo"."Bar" 
using gist(tsrange("DateTime"::timestamp, "DateTime"::timestamp, '[]'));

analyze "Foo"."Bar";
DateTime列表示一个时间点,因此时间戳范围表达式应具有包含的上下限“[]”

重写WHERE子句以使用相同的表达式

explain analyze
select "BarID"
from "Foo"."Bar"
where tsrange("DateTime"::timestamp, "DateTime"::timestamp, '[]') <@ tsrange('2015-01-01 00:00:00', '2015-01-01 01:00:00');
这个查询可以使用索引,它在大约有一百万行的表上运行大约需要半毫秒

"Bitmap Heap Scan on "Bar" (cost=10.19..859.53 rows=246 width=8) (actual time=0.195..0.551 rows=219 loops=1)" " Recheck Cond: (tsrange("DateTime", "DateTime", '[]'::text) <@ '["2015-01-01 00:00:00","2015-01-01 01:00:00")'::tsrange)" " -> Bitmap Index Scan on "Bar_tsrange_idx" (cost=0.00..10.13 rows=246 width=0) (actual time=0.160..0.160 rows=219 loops=1)" " Index Cond: (tsrange("DateTime", "DateTime", '[]'::text) <@ '["2015-01-01 00:00:00","2015-01-01 01:00:00")'::tsrange)" "Total runtime: 0.589 ms" 我猜是介于is和TSRANGE之间。 "Bitmap Heap Scan on "Bar" (cost=10.19..859.53 rows=246 width=8) (actual time=0.195..0.551 rows=219 loops=1)" " Recheck Cond: (tsrange("DateTime", "DateTime", '[]'::text) <@ '["2015-01-01 00:00:00","2015-01-01 01:00:00")'::tsrange)" " -> Bitmap Index Scan on "Bar_tsrange_idx" (cost=0.00..10.13 rows=246 width=0) (actual time=0.160..0.160 rows=219 loops=1)" " Index Cond: (tsrange("DateTime", "DateTime", '[]'::text) <@ '["2015-01-01 00:00:00","2015-01-01 01:00:00")'::tsrange)" "Total runtime: 0.589 ms"