簡體   English   中英

Join是否等效於帶有子查詢列的查詢?

[英]Is a Join equivalent to a query with a subquery for a column?

對不起,新手SQL問題,但不是同一回事:

select a.productid, sum(b.qty)
from table1 a
inner join table2 b on b.productid = a.productid
group by a.productid
;

select a.productid
,(select sum(b.qty) from table2 b where b.productid = a.productid)
from table1 a
group by a.productid
;

為什么有人會在選擇中使用上面的查詢,這是一些老派的事情要忘記使用,還是我應該考慮將其用於將來可能出現的一些問題?

不,它們實際上不是一回事。 有多種差異,但最明顯的就是join將篩選出任何不匹配的行。 相關子查詢將返回第一個表中的所有行。

也有其他差異。 如果第一個表中有重復的productidsum()將會不同。 執行計划將有所不同(因為結果集不同)。 在某些情況下,相關的子查詢會更快。

更一般地,在某些情況下,相關子查詢是表達邏輯的最簡單方法。 並且,如上所述,在某些情況下,它還可以產生最快的執行計划。

第一個查詢:

select a.productid, sum(b.qty)
from table1 a
inner join table2 b on b.productid = a.productid
group by a.productid

如果table2中沒有相應的值,則不會返回row。

第二個查詢就像LEFT JOIN

select a.productid
,(select sum(b.qty) from table2 b where b.productid = a.productid)
from table1 a
group by a.productid
<=>
select a.productid, sum(b.qty)
from table1 a
left join table2 b on b.productid = a.productid
group by a.productid

注意性能...內部聯接比子選擇要快得多。 子選擇遍歷所有匹配結果,因此復雜度為N x M ...導致性能不佳。 在大多數情況下,聯接具有更好的性能。

參見https://www.essentialsql.com/subquery-versus-inner-join/

暫無
暫無

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

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