Mysql JOIN两个嵌套查询

时间:2012-02-12 17:48:08

标签: mysql sql join inner-join nested-queries

在下面的查询中,我尝试使用customerNumber标识符将一个结果集加入另一个结果集。我想找到每个客户订购的金额和支付的金额。在没有Navicat Client

的帮助的情况下,sql不会执行
SELECT DISTINCT tabl1.customerNumber, 
                tabl1.amountOrdered, tabl2.amountPaid
FROM
(
     SELECT Distinct c.customerNumber, o.orderNumber, 
             SUM(od.quantityOrdered * od.priceEach) amountOrdered
     FROM ClassicModels.Customers c
     INNER JOIN ClassicModels.Orders o 
                ON c.customerNumber = o.customerNumber
     INNER JOIN ClassicModels.OrderDetails od 
                ON o.orderNumber = od.orderNumber
     GROUP BY od.orderNumber
     ORDER BY c.customerNumber
) tabl1
INNER JOIN 
(
     SELECT DISTINCT c.customerNumber, p.amount amountPaid
     FROM ClassicModels.Customers c 
     INNER JOIN ClassicModels.Payments p 
                ON c.customerNumber = p.customerNumber
 ) tabl2 ON tabl1.customerNumber = tabl2.customerNumber

1 个答案:

答案 0 :(得分:1)

如果您想选择每个客户的订购金额和支付金额,这个更简单的查询应该有效:

SELECT o.customerNumber as customerNumber, 
    SUM(od.quantityOrdered * od.priceEach) as amountOrdered, 
    SUM(p.amount) as amountPaid
FROM ClassicModels.Orders o
INNER JOIN ClassicModels.OrderDetails od
    ON o.OrderNumber = od.OrderNumber
LEFT JOIN ClassicModels.Payments p
    ON p.customerNumber = o.customerNumber
GROUP BY o.customerNumber