我正在创建一个汇总表,总结一天中的所有事件.

INSERT INTO graph_6(
  day,
  event_type,
  (SELECT COUNT(*) FROM event e 
                  WHERE event_type = e.event_type 
                  AND creation_time::DATE = sq.day)
FROM event_type
CROSS JOIN
    (SELECT generate_series(
                (SELECT '2014-01-01'::DATE),
                (SELECT '2014-01-02'::DATE),
                '1 day') as day) sq;

creation_time列被编入索引:

CREATE INDEX event_creation_time_date_idx ON event USING BTREE(creation_time);

但是,即使只查询两天的数据和少量事件(2014年1月1日至2日),查询也会运行相当长的时间.

查询中的EXPLAIN非常糟糕——它对event表进行顺序扫描,根本不使用索引:

->  Seq Scan on event e_1  (cost=0.00..12557.39 rows=531 width=38)
Filter: ... AND ((creation_time)::date = (generate_series(($12)::timestamp with time zone, ($13)::timestamp with time zone, '1 day'::interval))))

我认为这是因为我们比较了一个铸造值——creation_time::DATE,而不是creation_time.我试着为演员编制索引:

CREATE INDEX event_creation_time_date_idx ON event USING BTREE(creation_time::DATE);

但有一个错误:

ERROR: syntax error at or near "::"

Is there a way to utilize PostgreSQL indices on a timezone column casted to DATE?

推荐答案

索引声明中的表达式应包含在附加括号中,请try :

CREATE INDEX event_creation_time_date_idx ON event ((creation_time::DATE));

Postgresql相关问答推荐

计算两个子查询之间的差异

PostgreSQL(container)中使用80K子分区表处理共享内存不足错误

为MCV扩展统计设置统计目标

在PostGreSQL中获取最近日期的项目

我应该如何更新热门表?

PostgreSQL 中的 Datum 数据类型是什么以及它的用途是什么?

将 postgres 从属提升为主 node

如何将 NULL 值插入 UUID 而不是零

UPDATE implies move across partitions

带有初始数据的 docker postgres 不会在提交中持久化

如何通过我在 PostgreSQL 中的数据库获取列大小和类型

为什么 PostgreSQL 将用户和组合并为角色?

使用 pg_dump 和 psql -U postgres db_name < ... 移动数据库会导致ERROR: relation "table_name" does not exist

在 Spring Boot 应用程序中禁用表重新创建

在 PostgreSQL 数组中查找值的位置

Rails:PG :: InsufficientPrivilege:错误:permission denied for relation schema_migrations

在 PGAdmin 中搜索所有功能的文本

如何在postgresql中编写关于最大行数的约束?

在 PostgreSQL 中 Select 进入临时表?

如何更改 PostgreSQL 中的 REFERENCES?