Condition within JOIN or WHERE

后端 未结 9 1778
无人共我
无人共我 2020-11-22 10:16

Is there any difference (performance, best-practice, etc...) between putting a condition in the JOIN clause vs. the WHERE clause?

For example...

-- C         


        
9条回答
  •  旧时难觅i
    2020-11-22 11:10

    For inner joins I have not really noticed a difference (but as with all performance tuning, you need to check against your database under your conditions).

    However where you put the condition makes a huge difference if you are using left or right joins. For instance consider these two queries:

    SELECT *
    FROM dbo.Customers AS CUS 
    LEFT JOIN dbo.Orders AS ORD 
    ON CUS.CustomerID = ORD.CustomerID
    WHERE ORD.OrderDate >'20090515'
    
    SELECT *
    FROM dbo.Customers AS CUS 
    LEFT JOIN dbo.Orders AS ORD 
    ON CUS.CustomerID = ORD.CustomerID
    AND ORD.OrderDate >'20090515'
    

    The first will give you only those records that have an order dated later than May 15, 2009 thus converting the left join to an inner join.

    The second will give those records plus any customers with no orders. The results set is very different depending on where you put the condition. (Select * is for example purposes only, of course you should not use this in production code.)

    The exception to this is when you want to see only the records in one table but not the other. Then you use the where clause for the condition not the join.

    SELECT *
    FROM dbo.Customers AS CUS 
    LEFT JOIN dbo.Orders AS ORD 
    ON CUS.CustomerID = ORD.CustomerID
    WHERE ORD.OrderID is null
    

提交回复
热议问题