SQL COUNT乘以连接表中的条目

时间:2014-09-04 14:09:15

标签: mysql sql

我需要知道是否有更好的方法来运行以下查询。它返回错误的COUNT,因为要获取客户的地址,我必须加入customers_addresses表,而某些客户有多个地址。因此,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

1 个答案:

答案 0 :(得分:0)

您可以从内部查询中删除Customers_Addressses表,因为您可以在主查询中将其加入到您正在进行的操作中,因此在子查询中使用它是超级的。

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