左外连接未将第二个表显示为null

时间:2017-07-21 09:55:17

标签: mysql sql-server

表格结构 表1

account 
123
1234
12345
123456

table 2
account
123
1234
12345

我想在table1帐户上返回记录123456,在第2列不匹配表2时返回null

SQL
SELECT  table1.account, table2.account
from table1 
left outer join table2
on (table1.account= table2.account)

2 个答案:

答案 0 :(得分:0)

您的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'
        )

匹配第一个表中具有特定日期的行,以及第二个表中的null或特定日期。

注意日期文字。原始查询使用区域设置特定的格式。在不使用该格式的语言环境中,这很容易失败。别介意两位数的年份。

另一方面,

YYYYMMDD是明确的。

更新

删除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

答案 1 :(得分:0)

您的查询中一切正常,如果您使用任何where条款,请删除并检查,BTW我无法重现您的问题。 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
相关问题