使用 CTE 或连接所有表哪个更好

问题描述 投票:0回答:1

我有一个包含大量左连接的查询,并且我只检索了大多数左连接的一列,是对每个表使用 CTE 来仅检索需要的内容更好还是更好? 还是继续连接所有这些表更好,即使我每个左连接只需要一个表。

sql postgresql oracle
1个回答
0
投票

您想要从表中获得多少列并不重要。对于数据库管理系统

select t1.a, t2.b 
from t1
left join t2 using (x)

相同
select dt1.a, dt2.b 
from (select x, a from t1) dt1
left join (select x, b from t2) dt2 using (x)

with dt1 as (select x, a from t1) 
     dt2 as (select x, b from t2)
select dt1.a, dt2.b 
from dt1
left join dt2 using (x)

所以,保持简单。只需加入表格即可。这使得查询易于阅读,从而易于维护。

但是,一旦聚合数据,您通常会希望在加入之前进行聚合:

with upv as (select post_id, count(*) as total from upvotes group by post_id) 
     dnv as (select post_id, count(*) as total from downvotes group by post_id)
select
  post_id,
  upv.total as total_upvotes,
  dnv.total as total_downvotes
from upv
join dnv using (x)
order by post_id;
© www.soinside.com 2019 - 2024. All rights reserved.