简体   繁体   中英

SQL Server LEFT JOIN and WHERE clause

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

The problem happens when Table2 is null, so, the query returns nothing.

How do I leave the last part of the query AND Table2.IsDefault = 1 optional?

I've tried to short circuit the query using OR but I've found out that it works different than C#

SELECT ID, Name, Phone 
FROM Table1 
LEFT JOIN Table2 
ON Table1.ID = Table2.ID AND Table2.IsDefault = 1
WHERE Table1.ID = 12
 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.

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 :-)

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM