鉴于我在 DB 中有 3 个表,其中包含来自同一来源的不同数据片。所有表的结构都非常相似:
id | parent_id | timestamp | contents
每个表都有 parent_id(一个父到多个记录的关系)和时间戳索引。
我需要访问这些按时间排序的数据。目前我使用下一个查询:
prepare query3(bigint) as
select id, timestamp, contents, filter from
(select t1.id, t1.timestamp, t1.contents, 'filter1' as filter from table1 t1
where t1.parent_id = $1
union select t2.id, t2.timestamp, t2.contents, 'filter2' as filter from table2 t2
where t2.parent_id = $1
union select t3.id, t3.timestamp, t3.contents, 'filter3' as filter from table3 t3
where t3.parent_id = $1
) table_alias order by timestamp;
由于每个表中的数据非常多,因此每次执行此查询需要 2 到 3 分钟。据解释:650000行和Sort Method: external merge Disk: 186592kB
.
有没有办法在不更改架构的情况下优化检索执行时间,但构建更有效的查询或创建特定索引?
更新在这里添加了完整的解释分析结果。在这种情况下,查询中有 4 个表,但我相信在这种情况下 3 和 4 之间没有太大区别。
"Sort (cost=83569.28..83959.92 rows=156258 width=80) (actual time=2288.871..2442.318 rows=639225 loops=1)"
" Sort Key: t1.timestamp"
" Sort Method: external merge Disk: 186592kB"
" -> Unique (cost=52685.43..54638.65 rows=156258 width=154) (actual time=1572.274..1885.966 rows=639225 loops=1)"
" -> Sort (cost=52685.43..53076.07 rows=156258 width=154) (actual time=1572.273..1737.041 rows=639225 loops=1)"
" Sort Key: t1.id, t1.timestamp, t1.contents, ('table1'::text)"
" Sort Method: external merge Disk: 186624kB"
" -> Append (cost=0.00..14635.39 rows=156258 width=154) (actual time=0.070..447.375 rows=639225 loops=1)"
" -> Index Scan using table1_parent_id on table1 t1 (cost=0.00..285.08 rows=5668 width=109) (actual time=0.068..5.993 rows=9385 loops=1)"
" Index Cond: (parent_id = $1)"
" -> Index Scan using table2_parent_id on table2 t2 (cost=0.00..11249.13 rows=132927 width=168) (actual time=0.063..306.567 rows=589056 loops=1)"
" Index Cond: (parent_id = $1)"
" -> Index Scan using table3_parent_id on table3 t3 (cost=0.00..957.18 rows=4693 width=40) (actual time=25.234..82.381 rows=20176 loops=1)"
" Index Cond: (parent_id = $1)"
" -> Index Scan using table4_parent_id_idx on table4 t4 (cost=0.00..581.42 rows=12970 width=76) (actual time=0.029..5.894 rows=20608 loops=1)"
" Index Cond: (parent_id = $1)"
"Total runtime: 2489.569 ms"