2012-01-26 159 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 ...