簡體   English   中英

在PostgreSQL中哪個是更好的CTE或內部選擇

[英]Which is better CTE or Inner-Selects in PostgreSQL

下面給出的是我的兩個不同查詢執行 結果相同的示例

選擇查詢使用inner-select

   select p.product from
   (
      select * from tbl_a where productid not in (select productid from tbl_b)
   ) p 
   order by p.product

然后使用CTE選擇查詢

   with cte as 
   (
   select * from tbl_a where productid not in (select productid from tbl_b)
   )
   select product from cte order by product
  • 因此,我的問題是上述哪種方法好用? 在什么條件下可以使用它們?

Postgres總是實現CTE,這意味着CTE版本具有讀取和寫入數據的額外開銷。 (注意:在其他數據庫中不一定是正確的。)Postgres不會(必要)實現子查詢,因此版本應該更快。

編寫此查詢的一種更好的方法是完全放棄子查詢/ CTE:

  select a.product
  from tbl_a a
  where a.productid not in (select productid from tbl_b)
  order by a.product;

(我忽略的是,實際上not exists還是not exists left outer join總比not in存在更好。)

編寫查詢時,沒有使用CTE而不是子查詢的一般規則。 這取決於許多因素,尤其是是否對基礎表建立索引以及CTE在查詢中出現多少次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM