简体   繁体   中英

SQL COUNT multiplied by entries in join table

I need to know if there is a better way to run the following query. It is returning the wrong COUNT because to get the customer's addresses I have to join the customers_addresses table and some customers have more than one address. Therefore, the COUNT is being multiplied by the number of addresses the user has. I do not want it to do this, but I still want to obtain address information. Does anyone know how I could do this?

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

You can remove the Customers_Addressses table from the inner query because you can JOIN it outside in your main query what you're doing anyway so having it in the subquery is 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM