【发布时间】:2020-08-05 05:03:24
【问题描述】:
使用连接进行查询的最佳方式是什么?
- 先连接表,然后添加 where 条件
- 先用子查询添加where条件再加入
例如以下哪个查询的性能更好?
select * from person persons
inner join role roles on roles.person_id_fk = persons.id_pk
where roles.deleted is null
或
select * from person persons
inner join (select * from role roles where roles.deleted is null) as roles
on roles.person_id_fk = persons.id_pk
【问题讨论】:
-
第一个版本应该性能更好,因为它避免了显式子查询。出于教育目的,您应该在这两个查询上运行
EXPLAIN,以亲自了解 Postgres 将如何评估每个查询。 -
@Bawpotter 不,我想要最好的连接方式,但这个问题是关于查询执行的顺序。
-
如果有任何区别,我会感到非常惊讶。我很确定execution plan 对于两者都是相同的
标签: sql postgresql performance