SQL Server LEFT JOIN and WHERE clause

前端 未结 5 656
被撕碎了的回忆
被撕碎了的回忆 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:01

    Try this :

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

    You were almost there :-)

    0 讨论(0)
  • 2020-12-30 04:08

    Use a subquery to filter the results of Table 2 before they're joined with Table 1:

    SELECT ID, Name, Phone 
    FROM Table1 
    LEFT JOIN (SELECT * FROM Table2 WHERE IsDefault = 1) AS Table2 ON Table1.ID = Table2.ID
    WHERE Table1.ID = 12
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-30 04:17
    SELECT ID, Name, Phone 
    FROM Table1 
    LEFT JOIN Table2 
    ON Table1.ID = Table2.ID AND Table2.IsDefault = 1
    WHERE Table1.ID = 12
    
    0 讨论(0)
  • 2020-12-30 04:17
    SELECT ID, Name, Phone FROM Table1 
      LEFT JOIN Table2 ON Table1.ID = Table2.ID
      WHERE Table1.ID = 12 
        AND (Table2.IsDefault IS NULL OR Table2.IsDefault = 1);
    
    0 讨论(0)
提交回复
热议问题