使用 if 条件进行内部连接 [英] Inner join with if condition

查看:29
本文介绍了使用 if 条件进行内部连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个带有内部连接的查询,只有当表 1 的 RepID 存在于表 2 中时,否则不连接表 2.对于我在下面使用的查询,如果表 2 中不存在 repID,我不会从两个表中获取.这怎么可能?我使用的是 sql server 2005.在此先感谢您!

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

推荐答案

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

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

这篇关于使用 if 条件进行内部连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆