[英]Left outer join not showing second table as null
表结构表1
account
123
1234
12345
123456
table 2
account
123
1234
12345
我想返回表记录123456
表1上的记录,并为列2不匹配表2时为null
SQL
SELECT table1.account, table2.account
from table1
left outer join table2
on (table1.account= table2.account)
您的where
语句明确要求使用table2.dates = '19-jul-17'
非空行
您应该修改查询以检查是否为空:
SELECT
table1.account, table2.account
from table1
left outer join table2
on (table1.account= table2.account)
where
t1.dates='20170719'
and ( table2.account is NULL
or
table2.dates = '20170719'
)
这将匹配在第一个表中具有特定日期,在第二个表中具有空或特定日期的行。
注意日期文字。 原始查询使用特定于语言环境的格式。 在不使用该格式的语言环境中,这很容易失败。 没关系两位数字年份。
另一方面, YYYYMMDD
是明确的。
UPDATE
除去where
子句后,将按预期返回NULL:
declare @table1 table (id int)
declare @table2 table (id int)
insert into @table1
values
(123 ),
(1234 ),
(12345 ),
(123456)
insert into @table2
values
(123 ),
(1234 ),
(12345)
SELECT t1.id, t2.id
from @table1 t1
left outer join @table2 t2
on (t1.id= t2.id)
返回
id id
123 123
1234 1234
12345 12345
123456 NULL
如果问题是“如何获取不匹配的行”,则答案是使用WHERE tabl2.ID IS NULL
在您的查询中一切正常,如果您使用任何where
子句,请删除并检查,顺便说一句,我无法重现您的问题。 PFB尝试,查询给出预期结果
create table #tmp1( ID int)
create table #tmp2( ID int)
Insert into #tmp1 values('123')
Insert into #tmp1 values ('1234')
Insert into #tmp1 values ('12345')
Insert into #tmp1 values ('123456')
Insert into #tmp2 values('123')
Insert into #tmp2 values ('1234')
Insert into #tmp2 values ('12345')
select * from #tmp1
select * from #tmp2
SELECT #tmp1.ID, #tmp2.ID from #tmp1 left outer join #tmp2 on (#tmp1.ID=#tmp2.ID)
drop table #tmp1
drop table #tmp2
结果是:
ID ID
123 123
1234 1234
12345 12345
123456 NULL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.