次のクエリを検討してください。
select a.id from a
where
a.id in (select b.a_id from b where b.x='x1' and b.y='y1') and
a.id in (select b.a_id from b where b.x='x2' and b.y='y2')
order by a.date desc
limit 20
どちらがより高速なものに書き換え可能である必要があります:
select a.id from a inner join b as b1 on (a.id=b1.a_id) inner join b as b2 on (a.id=b2.a_id)
where
b1.x='x1' and b1.y='y1' and
b2.x='x2' and b2.y='y2'
order by a.date desc
limit 20
ソース コードを変更してクエリを書き直すのは非常に複雑になるため (特に Django を使用している場合)、できるだけ避けたいと考えています。
したがって、PostgreSQL がサブクエリを結合に折りたたむのはいつで、そうでないのはいつなのだろうか?
これが単純化されたデータ モデルです。
Table "public.a"
Column | Type | Modifiers
-------------------+------------------------+-------------------------------------------------------------
id | integer | not null default nextval('a_id_seq'::regclass)
date | date |
content | character varying(256) |
Indexes:
"a_pkey" PRIMARY KEY, btree (id)
"a_id_date" btree (id, date)
Referenced by:
TABLE "b" CONSTRAINT "a_id_refs_id_6e634433343d4435353" FOREIGN KEY (a_id) REFERENCES a(id) DEFERRABLE INITIALLY DEFERRED
Table "public.b"
Column | Type | Modifiers
----------+-----------+-----------
a_id | integer | not null
x | text | not null
y | text | not null
Indexes:
"b_x_y_a_id" UNIQUE CONSTRAINT, btree (x, y, a_id)
Foreign-key constraints:
"a_id_refs_id_6e634433343d4435353" FOREIGN KEY (a_id) REFERENCES a(id) DEFERRABLE INITIALLY DEFERRED
- a には 700 万行あります
- b には 7000 万行あります
- bx のカーディナリティ = ~100
- by = ~100000 のカーディナリティ
- bx のカーディナリティ by = ~150000
- テーブル c、d、および e が b と同じ構造を持ち、追加で使用して結果の a.ids をさらに減らすことができると想像してください。
PostgreSQL のバージョン、クエリをテストしました。
PostgreSQL 9.2.7 on x86_64-suse-linux-gnu, compiled by gcc (SUSE Linux) 4.7.2 20130108 [gcc-4_7-branch revision 195012], 64-bit
PostgreSQL 9.4beta1 on x86_64-suse-linux-gnu, compiled by gcc (SUSE Linux) 4.7.2 20130108 [gcc-4_7-branch revision 195012], 64-bit
クエリ プラン (空のファイル キャッシュとメモリ キャッシュを使用):