【发布时间】:2019-11-26 04:40:45
【问题描述】:
我使用以下代码设置我的 Postgresql 数据库,这将在 test1 表和 test2 表中创建 1000 万条记录。
CREATE TABLE test1(
id serial PRIMARY KEY,
val text
);
CREATE TABLE test2(
test1_id integer,
FOREIGN KEY (test1_id) REFERENCES test1(id)
);
do $$
begin
for r in 1..10000000 loop
insert into test1(id, val) values(r, 10000000-1);
insert into test2(test1_id) values(r);
end loop;
end;
$$;
CREATE INDEX test1_val ON test1 USING btree(val);
现在我执行以下连接:
SELECT * FROM test1 join test2 ON test1.id=test2.test1_id WHERE val='55555';
并且连接需要超过 1 秒才能完成。
这是在查询上运行解释的输出:
QUERY PLAN
------------------------------------------------------------------------------------
Hash Join (cost=8.46..181757.13 rows=1 width=15)
Hash Cond: (test2.test1_id = test1.id)
-> Seq Scan on test2 (cost=0.00..144248.48 rows=10000048 width=4)
-> Hash (cost=8.45..8.45 rows=1 width=11)
-> Index Scan using test1_val on test1 (cost=0.44..8.45 rows=1 width=11)
Index Cond: (val = '55555'::text)
(6 rows)
该示例更多用于说明目的,在真实场景中 test2 表上会有更多属性。同样在真实场景中,test1 和 test2 上的记录可能会更多,并且连接完成所需的时间会超过 1 秒。
有没有更有效的方法来构建这个数据库的索引,或者执行上面的查询?
【问题讨论】:
标签: sql postgresql join indexing