2012-01-26 131 views
0

仅供参考 - 此查询从excel运行。我有提示字段来设置日期范围。SQL Server查询INNER JOIN - 缺少条目

原来这里是工作的查询我从别人的了:

SELECT 
    SalesInvoiceItems.FreeTextItem, SalesInvoiceItems.Product, 
    SalesInvoiceItems.ItemDescription, SalesInvoiceItems.Quantity, 
    SalesInvoiceItems.ItemValue, Customers.CustomerId, Customers.CustomerName, 
    SalesInvoices.SalesInvoiceId, SalesInvoices.EffectiveDate, Countries.CountryId, 
    SalesInvoiceItems.ItemType 
FROM 
    Winman.dbo.Countries Countries, Winman.dbo.Customers Customers, 
    Winman.dbo.Products Products, Winman.dbo.SalesInvoiceItems SalesInvoiceItems, 
    Winman.dbo.SalesInvoices SalesInvoices 
WHERE 
    Customers.Customer = SalesInvoices.Customer 
    AND SalesInvoiceItems.SalesInvoice = SalesInvoices.SalesInvoice 
    AND Customers.Country = Countries.Country 
    AND ((SalesInvoices.SystemType='F') 
    AND (SalesInvoiceItems.ItemType<>'T') 
    AND (SalesInvoices.EffectiveDate>=? And SalesInvoices.EffectiveDate<=?) 
    AND (SalesInvoiceItems.ItemValue<>$0)) 
ORDER BY 
    SalesInvoiceItems.Quantity DESC 
这里

重要的一点是ItemType(它只能是T,至极被排除在外,P - 对产品和N - 自由文本项)

我需要添加表Products,检索ProductID。显然,添加以下代码WHERE条款:

AND Products.Product = SalesInvoiceItems.Product 

将无法​​带来任何自由文本项目,因为不是产品。

所以我改写查询与联接希望能解决我的问题(抚育项目的P和N型):

SELECT 
    Products.ProductId, 
    SalesInvoiceItems.FreeTextItem, 
    SalesInvoiceItems.Product, 
    SalesInvoiceItems.ItemDescription, 
    SalesInvoiceItems.Quantity, 
    SalesInvoiceItems.ItemValue, 
    Customers.CustomerId, 
    Customers.CustomerName, 
    SalesInvoices.SalesInvoiceId, 
    SalesInvoices.EffectiveDate, 
    Countries.CountryId, 
    SalesInvoiceItems.ItemType 
FROM 
    Winman.dbo.SalesInvoiceItems AS SalesInvoiceItems 
INNER JOIN 
    Winman.dbo.Products AS Products ON Products.Product = SalesInvoiceItems.Product 
INNER JOIN 
    Winman.dbo.SalesInvoices AS SalesInvoices ON SalesInvoices.SalesInvoice= SalesInvoiceItems.SalesInvoice 
INNER JOIN 
    Winman.dbo.Customers AS Customers ON Customers.Customer = SalesInvoices.Customer 
INNER JOIN 
    Winman.dbo.Countries AS Countries ON Countries.Country = Customers.Country 
WHERE 
    ((SalesInvoices.SystemType='F') 
    AND (SalesInvoiceItems.ItemType<>'T') 
    AND (SalesInvoices.EffectiveDate >= ? And SalesInvoices.EffectiveDate <= ?) 
    AND (SalesInvoiceItems.ItemValue <> $0) 
    ) 
ORDER BY 
    SalesInvoiceItems.Quantity DESC 

但仍作为行为和 - 而忽略自由文本项目!我明显错过了一些东西..尽管自由文本项目没有ProductID,我怎样才能带来产品和免费文本项目?

回答

2

您的旧查询使用旧式JOIN语法。完全放弃这种隐式(内部)加入以支持显式加入是一件好事。

使用时明确连接,你现在有选择INNEROUTER连接(ref. MSDN)之间。

仅当 表中至少有一行匹配连接条件时,内部连接才返回行。内部连接消除与其他表中的行不匹配的行 。 外部连接 但是,只要这些行满足任何WHERE或具有搜索条件的任何WHERE或 ,就返回FROM子句中提到的至少一个表或视图 中的所有行。

因此,在针对您的问题,改变你的INNER JOIN s到LEFT JOIN小号

+0

是课程!!!我甚至没有想到!尽管我不得不与微软查询进行争夺以使其接受它... – Elen

0

不知道我理解正确,但尝试改变:

INNER JOIN Winman.dbo.Products AS Products ON ... 

到:的

LEFT JOIN Winman.dbo.Products AS Products ON ...