INNER JOIN vs INNER JOIN (SELECT . FROM)

后端 未结 4 1757
栀梦
栀梦 2021-02-01 00:27

Is there any difference in terms of performance between these two versions of the same query?

--Version 1
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN Sal         


        
4条回答
  •  鱼传尺愫
    2021-02-01 01:03

    You did the right thing by checking from query plans. But I have 100% confidence in version 2. It is faster when the number off records are on the very high side.

    My database has around 1,000,000 records and this is exactly the scenario where the query plan shows the difference between both the queries. Further, instead of using a where clause, if you use it in the join itself, it makes the query faster :
    SELECT p.Name, s.OrderQty
    FROM Product p
    INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID WHERE p.isactive = 1

    The better version of this query is :

    SELECT p.Name, s.OrderQty
    FROM Product p
    INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID AND p.isactive = 1

    (Assuming isactive is a field in product table which represents the active/inactive products).

提交回复
热议问题