简体   繁体   English

SQL Server LEFT JOIN和WHERE子句

[英]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. Table2为null时会发生问题,因此查询不返回任何内容。

How do I leave the last part of the query AND Table2.IsDefault = 1 optional? 如何保留查询的最后部分AND Table2.IsDefault = 1可选?

I've tried to short circuit the query using OR but I've found out that it works different than C# 我试图使用OR来短路查询,但我发现它与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. 因为它是一个OUTER连接,所以如果匹配失败,你仍然会保留任何Table1信息,并且给出“Table2将始终返回1个条目”的语句,你不会冒着通过移动条件来过滤其他连接结果的风险。 You will get the same results as placing the condition in the WHERE clause. 您将获得将条件放在WHERE子句中相同的结果。

The reason to move the conidtion to the ON clause is that the COALESCE() , ISNULL() , and OR all cause problems for indexes. 将conidtion移动到ON子句的原因是COALESCE()ISNULL()OR都会导致索引出现问题。 With the condition in the ON clause, we don't need any of those, and so should end up with a better execution plan. 根据ON子句中的条件,我们不需要任何这些条件,因此最终应该有一个更好的执行计划。

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: 在与表1结合使用之前,使用子查询过滤表2的结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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