我正在创建一个汇总表,总结一天中的所有事件.
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?