SQL Server LEFT JOIN and WHERE clause

前端 未结 5 692
被撕碎了的回忆
被撕碎了的回忆 2020-12-30 03:53

Here is my code

SELECT ID, Name, Phone 
FROM Table1 
LEFT JOIN Table2 ON Table1.ID = Table2.ID
WHERE Table1.ID = 12 AND Table2.IsDefault = 1
<
5条回答
  •  没有蜡笔的小新
    2020-12-30 04:13

     AND COALESCE(Table2.IsDefault,1) = 1
    

    Reading the comments, it looks like your best solution is actually to move the condition to the join:

    SELECT ID, Name, Phone 
    FROM Table1 
    LEFT JOIN Table2 ON Table1.ID = Table2.ID AND Table2.IsDefault = 1
    WHERE Table1.ID = 12 
    

    Because it's an OUTER join, you'll still keep any Table1 information if the match fails, and given the statement that "Table2 will always return 1 entry" you're not risking filtering additional join results by moving the condition. You will get the same results as placing the condition in the WHERE clause.

    The reason to move the conidtion to the ON clause is that the COALESCE(), ISNULL(), and OR all cause problems for indexes. With the condition in the ON clause, we don't need any of those, and so should end up with a better execution plan.

提交回复
热议问题