Join 返回空但子查询不返回空

问题描述 投票:0回答:1

我有2张桌子:

发票

CustomerInvoiceID - PK
RecordLocator - Text
createdDate - date

简化发票

CustomerInvoiceID - PK / FK Invoices
CountryCode - text
VatPercentage - number
SubtotalAmount - number
TotalAmount - number

如果我运行以下查询:

select  
    si.CountryCode, 
    si.RecordLocator, 
    si.CustomerInvoiceID, 
    i.CreatedDate,  
    i.VatPercentage, 
    si.SubTotalAmount, 
    si.TotalAmount
from
    SimpliedInvoice si , invoice i 
where 
    si.CustomerInvoiceID = i.CustomerInvoiceID
    and si.CountryCode = 'GR'

我的结果是一个空数据集。

但是如果我运行这个查询:

select * 
from SimpliedInvoice
where CustomerInvoiceID in (select CustomerInvoiceID 
                            from Invoice 
                            where CountryCode = 'GR')

我获得了大量数据。

我不明白为什么,有什么想法吗?

sql-server join
1个回答
0
投票

好吧,在您的第一个查询中,您检查

SimplifiedInvoice
表(别名
si
)中的 CountryCode = 'GR' -

where 
    ....
    and si.CountryCode = 'GR'
        *********************

但是在第二个查询中,您正在子查询中测试同一国家/地区代码的发票表:

where CustomerInvoiceID in (select CustomerInvoiceID 
                            from Invoice 
                                 *******  
                            where CountryCode = 'GR')
                                  ******************

因此将您的第一个查询更改为:

select  
    si.CountryCode, 
    si.RecordLocator, 
    si.CustomerInvoiceID, 
    i.CreatedDate,  
    i.VatPercentage, 
    si.SubTotalAmount, 
    si.TotalAmount
from
    SimpliedInvoice si 
inner join
    invoice i on si.CustomerInvoiceID = i.CustomerInvoiceID
where 
    i.CountryCode = 'GR'

您应该得到返回的同一组数据

© www.soinside.com 2019 - 2024. All rights reserved.