2014-09-04 86 views
0

我需要知道是否有更好的方法來運行以下查詢。它正在返回錯誤的COUNT號碼,因爲要獲取客戶的地址,我必須加入customers_addresses表,並且某些客戶擁有多個地址。因此,COUNT正乘以用戶擁有的地址數量。我不希望它這樣做,但我仍然想獲取地址信息。有誰知道我該怎麼做?SQL COUNT乘以連接表中的條目

SELECT 
    Customers.UserID, 
    Customers.FirstName, 
    Customers.LastName, 
    Customers_Addresses.Address1, 
    Customers_Addresses.City, 
    Customers_Addresses.Region, 
    TotalOrders 
FROM 
    (SELECT 
     Customers.UserID, 
     Customers.FirstName, 
     Customers.LastName, 
     Customers_Addresses.Address1, 
     Customers_Addresses.City, 
     Customers_Addresses.Region, 
     Customers.GroupID, 
     COUNT(Orders.OrderID) AS TotalOrders, 
     SUM(Orders.TotalCost) AS TotalSalesOfAllTime 
    FROM 
     Orders 
     INNER JOIN Customers ON Customers.UserID = Orders.UserID 
     INNER JOIN Groups ON Customers.GroupID = Groups.GroupID 
     INNER JOIN Customers_Addresses ON Customers.UserID = Customers_Addresses.UserID 
    GROUP BY Orders.UserID 
) Customers 
INNER JOIN Customers_Addresses ON Customers.UserID = Customers_Addresses.UserID 
WHERE 
    1 = 1 
     AND Customers.UserID BETWEEN 2570 AND 2570 
+0

通過格式化您的問題中的查詢開始。 – 2014-09-04 14:10:50

+0

您是否考慮過MySQL的[GROUP_CONCAT](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat)函數? – 2014-09-04 14:44:41

回答

0

您可以從內部查詢刪除Customers_Addressses表,因爲你可以在你的主查詢外JOIN它,你在做什麼,反正所以有它的子查詢superflous。

SELECT 
Customers.UserID, 
Customers.FirstName, 
Customers.LastName, 
Customers_Addresses.Address1, 
Customers_Addresses.City, 
Customers_Addresses.Region, 
TotalOrders 
FROM 
(SELECT 
    Customers.UserID, 
    Customers.FirstName, 
    Customers.LastName, 
    Customers.GroupID, 
    COUNT(Orders.OrderID) AS TotalOrders, 
    SUM(Orders.TotalCost) AS TotalSalesOfAllTime 
FROM 
    Orders 
    INNER JOIN Customers ON Customers.UserID = Orders.UserID 
    INNER JOIN Groups ON Customers.GroupID = Groups.GroupID 
GROUP BY Orders.UserID 
) Customers 
INNER JOIN Customers_Addresses ON Customers.UserID = Customers_Addresses.UserID 
WHERE Customers.UserID BETWEEN 2570 AND 2570 
+0

完美!這解決了COUNT問題,但由於外部查詢中的customer_addresses的內部連接,我仍然有客戶重複兩次。有沒有辦法來彙總數據? – CaitlinHavener 2014-09-04 14:29:01