我有以下疑問:合併這兩個查詢到一個查詢
SELECT Sites.EDISID, Sites.[Name], (SUM(DLData.Quantity)/8) AS TiedDispense
FROM Sites
JOIN UserSites
ON UserSites.EDISID = Sites.EDISID
JOIN Users
ON Users.[ID] = UserSites.UserID
JOIN MasterDates
ON MasterDates.EDISID = UserSites.EDISID
JOIN DLData
ON DLData.DownloadID = MasterDates.[ID]
JOIN Products
ON Products.[ID] = DLData.Product
LEFT JOIN SiteProductTies
ON SiteProductTies.EDISID = UserSites.EDISID
AND SiteProductTies.ProductID = Products.[ID]
LEFT JOIN SiteProductCategoryTies
ON SiteProductCategoryTies.EDISID = UserSites.EDISID
AND SiteProductCategoryTies.ProductCategoryID = Products.CategoryID
WHERE Users.[ID] = @UserID
AND (COALESCE(SiteProductTies.Tied, SiteProductCategoryTies.Tied, Products.Tied) = @Tied OR @Tied IS NULL)
AND MasterDates.[Date] BETWEEN @From AND @To
AND MasterDates.[Date] >= Sites.SiteOnline
GROUP BY Sites.EDISID, Sites.[Name]
SELECT Sites.EDISID, Sites.[Name], SUM(Delivery.Quantity) AS TiedDelivered
FROM Sites
JOIN UserSites
ON UserSites.EDISID = Sites.EDISID
JOIN Users
ON Users.[ID] = UserSites.UserID
JOIN MasterDates
ON MasterDates.EDISID = UserSites.EDISID
JOIN Delivery
ON Delivery.DeliveryID = MasterDates.[ID]
JOIN Products
ON Products.[ID] = Delivery.Product
LEFT JOIN SiteProductTies
ON SiteProductTies.EDISID = UserSites.EDISID
AND SiteProductTies.ProductID = Products.[ID]
LEFT JOIN SiteProductCategoryTies
ON SiteProductCategoryTies.EDISID = UserSites.EDISID
AND SiteProductCategoryTies.ProductCategoryID = Products.CategoryID
WHERE Users.[ID] = @UserID
AND (COALESCE(SiteProductTies.Tied, SiteProductCategoryTies.Tied, Products.Tied) = @Tied OR @Tied IS NULL)
AND MasterDates.[Date] BETWEEN @From AND @To
AND MasterDates.[Date] >= Sites.SiteOnline
GROUP BY Sites.EDISID, Sites.[Name]
正如你可以看到他們是非常相似的 - 只是關於查詢是否是用於DLData
或Delivery
是不同的線路。其中一個返還總額,另一個返還總額。
當前我在第三個查詢中將它們用作兩個單獨的子查詢。單獨他們大約需要1-2秒。作爲兩個子查詢,它們需要6到10秒(取決於負載),並且都返回47行(儘管它們總共觸及數千行)。
我在想,合併它們會給我一個體面的加速 - 尤其是當這個查詢將被稱爲很多。
但是我的嘗試失敗了,因爲當我嘗試將兩者結合時,行數發生了變化。我嘗試了各種JOIN組合,但沒有返回正確的結果。
SO'ers有什麼建議嗎?
不,因爲這個想法是將這些簡化爲單個查詢。唯一的相關領域是SUM。其餘的是與已知結果進行比較。 – 2009-11-11 13:58:01