2012-07-23 11 views
1

동일한 원점의 다른 데이터 조각을 포함하는 DB에 3 개의 테이블이 있습니다. 모든 테이블은 매우 유사한 구조를 가지고 :많은 테이블의 집계 데이터

id | parent_id | timestamp | contents 

각 테이블은 PARENT_ID하고 타임 스탬프 지수 (많은 레코드 관계 부모).

시간별로 정렬 된이 데이터에 액세스해야합니다. 현재 다음 쿼리를 사용하고 있습니다.

각 테이블에 꽤 많은 데이터가 있으므로이 쿼리를 실행할 때마다 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" 
+1

먼저 임시 테이블에 모든 것을 넣으려고 했습니까? –

+2

색인 parent_id – Samson

+0

전체 설명 게시 – Samson

답변

1

노동 조합의 중복을 제거하면 많은 시간이 낭비됩니다.

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 all 
     (select t2.id, t2.timestamp, t2.contents, 'filter2' as filter 
     from table2 t2 
     where t2.parent_id = $1 
     ) 
     union all 
     (select t3.id, t3.timestamp, t3.contents, 'filter3' as filter 
     from table3 t3 
     where t3.parent_id = $1 
     ) 
    ) table_alias 
order by timestamp; 

이 방법을 효과적으로 사용하려면 세 테이블 각각에 대해 parent_id에 대한 색인이 있어야합니다. 이러한 변화로 인해, 그것은 꽤 불타야합니다.

+0

확인. 원하는대로 쿼리 변환 : – Vestel

+0

OK. 원하는대로 쿼리 변환 : 처음 쿼리 실행 : 60 초, 다음 10-11 초 호출. 업데이트 된 쿼리 실행 : 9 초, 다음에 9-11 초가 걸립니다. – Vestel

관련 문제