我需要知道是否有更好的方法來運行以下查詢。它正在返回錯誤的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
通過格式化您的問題中的查詢開始。 – 2014-09-04 14:10:50
您是否考慮過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