简体   繁体   中英

Left outer join not showing second table as null

Table structre table 1

account 
123
1234
12345
123456

table 2
account
123
1234
12345

I want to return table a record 123456 on account for table1 and null for column 2 when it doesnt match table 2

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

Your where statement explicitly asked for non-null rows with table2.dates = '19-jul-17'

You should modify your query to check for nulls:

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

This matches rows that have a specific date in the first table, and either null or a specific date on the second.

Note the date literal. The original query used a locale-specific format. This can fail easily faile in locales that don't use that format. Never mind the two digit year.

YYYYMMDD on the other hand is unambiguous.

UPDATE

Once the where clause is removed, NULLs are returned as expected :

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)

Returns

id     id
123    123
1234   1234
12345  12345
123456 NULL

If the question is "how do I get the non-matching row" the answer is use WHERE tabl2.ID IS NULL

Everything is OK in your query, If you are using any where clause, please remove and check, BTW i am not able to reproduce your issue. PFB attempt, The query gives expected result

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

The result is:

ID  ID
123 123
1234    1234
12345   12345
123456  NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM