简体   繁体   English

如何优化Postgres的SQL查询?

[英]How to optimize the SQL query for Postgres?

I have a SQL query similar as below: 我有一个类似于以下的SQL查询:

select *
from TableA
  left outer join TableB on...
  left outer join TableC on...
  ...
  left outer join TableN on...

where
  TableA.id in (subquery);

This query takes a long time to execute and I checked the execution plan of it and and found out that it did the joins first and then the where. 该查询需要很长时间才能执行,我检查了该查询的执行计划,发现该查询先执行联接,然后执行where。 However, the joins takes long time to finish. 但是,连接需要很长时间才能完成。 I run the same query against Oracle and Oracle did the optimization so that it does the 'where' part together with the joins and so that the time is much short. 我对Oracle运行相同的查询,并且Oracle进行了优化,以便它与联接一起执行“ where”部分,因此时间很短。

My question is: how can I optimize the SQL query so that Postgres can do the 'where' part first? 我的问题是:如何优化SQL查询,以便Postgres可以首先执行“ where”部分?

PS: I cannot add the subquery into the 'from' part using an inner join because I am using Hibernate and it doesn't support subquery in 'from' part. PS:我无法使用内部联接将子查询添加到“ from”部分,因为我正在使用Hibernate,并且它不支持“ from”部分中的子查询。

As already discussed widely in the comments to your post there is a possibility that the "FROM (subquery) tblalias" approach might still work, so here it is as pseudocode again: 正如您的帖子评论中已经广泛讨论的那样,“ FROM(子查询)tblalias”方法可能仍会起作用,因此这里还是伪代码:

select * from (
  select * from TableA where id in (subquery) 
) tblA
left outer join TableB on...
left outer join TableC on...
...
left outer join TableN on...

But - who knows for definite, as pseudocode cannot be tested ... 但是-谁知道是确定的,因为伪代码无法测试...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM