我有两个表:
create table animal
(
aid integer,
cid integer,
aname varchar(255) default NULL::character varying,
species text
);
create table daily_feeds
(
aid integer,
zid integer,
shift integer,
menu integer
);
Run Code Online (Sandbox Code Playgroud)
和一个查询:
SELECT
aname,
shift
FROM animal
NATURAL JOIN daily_feeds
WHERE menu = 1;
Run Code Online (Sandbox Code Playgroud)
餐桌动物包含大约 40000 行,表 daily_feeds 包含大约 80000 行,每只动物 2 行。
我认为在用于连接animal.aid和daily_feeds.aid的列上添加索引可能会导致不同的执行计划并提高性能。
create index aaid on animal (aid);
create index daid on daily_feeds using btree (aid);
Run Code Online (Sandbox Code Playgroud)
这不会发生。这是为什么?
显然,这是一个非常简单且学术性的示例,我试图用它来了解有关数据库查询优化的更多信息。
编辑:
添加没有索引时的执行计划:
Hash Join (cost=1439.24..2488.23 rows=499 width=10) …
Run Code Online (Sandbox Code Playgroud)