考虑以下查询:
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 的基数,由 = ~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
查询计划(带有空文件缓存和内存缓存):