Sql server 这是在左外部联接中筛选右表的唯一方法吗?

Sql server 这是在左外部联接中筛选右表的唯一方法吗?,sql-server,left-join,Sql Server,Left Join,我将客户余额存储在他们自己的表中。客户余额表每天都会获得一组新的记录(反映当天的余额),但包含其他日期(yyyy-mm-dd)的余额。我想从accountinformation获取所有英国客户,并从balances获取他们昨天的余额。我想包括会计信息中的行,即使在余额中没有相应的记录(昨天的记录) select firstname,lastname,accountnumber,balance from accountinformation i left outer join balances

我将客户余额存储在他们自己的表中。客户余额表每天都会获得一组新的记录(反映当天的余额),但包含其他日期(yyyy-mm-dd)的余额。我想从
accountinformation
获取所有英国客户,并从
balances
获取他们昨天的余额。我想包括
会计信息
中的行,即使在
余额
中没有相应的记录(昨天的记录)

select firstname,lastname,accountnumber,balance from accountinformation i 
left outer join balances b 
on i.accountnumber = b.account
where country = 'UK' and status = 'OPEN'
and (b.date = '2014-04-10' or b.date is null)
。。。如果
余额中没有相应的行,则不满足显示
会计信息中的行的要求。我必须这样写查询

select firstname,lastname,accountnumber,balance from accountinformation i 
left outer join (select * from balances where date = '2014-04-10') b 
on i.accountnumber = b.account
where country = 'UK' and status = 'OPEN'

。。以获得所需的行为。为了保证正确性,我想知道是否有更正确的方法来过滤
左外部联接中的左表?

您可以这样做

select firstname,lastname,accountnumber,balance from accountinformation i 
left outer join balances b 
on i.accountnumber = b.account and b.date = '2014-04-10'
where country = 'UK' and status = 'OPEN'

也许可以在i.accountnumber=b.account和b.date='2014-04-10'
上尝试
左外部连接余额b,省略where子句中的
和(b.date='2014-04-10'或b.date为null)
。顺便说一句,您的第一条语句在Sybase ASE上可以正常工作,在MySQL上也可以正常工作。。。那么,是否将过滤器包含在“打开”部分?听起来不错。我试试看。汉诺·宾德,几秒钟前发的。我认为你的回答比我草率的评论更清楚地说明了问题的症结所在将
b.date='2014-04-10'
作为WHERE子句中与此相反的第三个条件有什么区别?谢谢。这是可行的,现在我明白了,这也是有道理的!knightwisp是我能解释我认为它是如何工作的最好方法,它是限制查询结果的条件。将其置于联接上会限制联接表的结果。如果有道理的话,哈哈