簡體   English   中英

左外部聯接未將第二個表顯示為null

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM