我有一个包含大量左连接的查询,并且我只检索了大多数左连接的一列,是对每个表使用 CTE 来仅检索需要的内容更好还是更好? 还是继续连接所有这些表更好,即使我每个左连接只需要一个表。
您想要从表中获得多少列并不重要。对于数据库管理系统
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;