内心与条件[英] Inner join with if condition

本文是小编为大家收集整理的关于内心与条件的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我试图在表2中存在table1的compid(如果不加入table2)中编写一个与内连接的查询.使用我在下面使用的查询,如果copid在表2中不存在,我不会从两个表中获得.这怎么可能?我正在使用SQL Server2005.谢谢您!

Select * from Table1
inner join Table2 on Table1.RepID = Table2.RepID
where Table1.Date = @Date
order by Table1.Date desc

推荐答案

只有在连接的两侧找到匹配项时,内部连接才会返回一行.如果您正在寻找可以从Table1返回所有行但仅在找到匹配时从Table2中返回所有行的东西,则需要一个左外连接:

select * from Table1 as t1
left outer join Table2 as t2
    on t1.RepID = t2.RepID
where t1.Date = @Date
order by t1.Date desc

其他推荐答案

尝试"左联接"而不是"内联".

单词"左"含义"始终包含加入左侧表的每个记录",在这种情况下,table1,因为您将写下:table1左JOIN table2,而" table1"在此左侧一对! : - )

其他推荐答案

听起来您实际想要的是左外的加入,不是吗?

本文地址:https://itbaoku.cn/post/2786894.html

问题描述

I was trying to write a query with inner join only if RepID of Table1 exists in Table2, if not do not join table2. With the query that i used below, i do not get from both the tables if repID doesnot exist in Table2. How is it possible? I am using sql server 2005. Thank you in advance!

Select * from Table1
inner join Table2 on Table1.RepID = Table2.RepID
where Table1.Date = @Date
order by Table1.Date desc

推荐答案

An inner join will only return a row if matches are found in both sides of the join. If you're looking for something that will return all rows from Table1 but only records from Table2 when a match is found, you want a left outer join:

select * from Table1 as t1
left outer join Table2 as t2
    on t1.RepID = t2.RepID
where t1.Date = @Date
order by t1.Date desc

其他推荐答案

Try "LEFT JOIN" instead of "INNER JOIN".

The word "LEFT" means "Always include every record from the table on the LEFT of the join," in this case Table1, since you will write: Table1 LEFT JOIN Table2, and "Table1" is on the left of that pair! :-)

其他推荐答案

it sounds like what you actually want is a left outer join, isnt it?