我如何子查询两个连接?

时间:2016-10-05 21:23:04

标签: mysql join subquery

我创建了两个查询,它们都返回所需的结果,彼此独立。我正在尝试加入它们,使返回的值为customerName,Amount Ordered和Amount Paid。

目前,此查询有效,但仅返回customerName。如何让查询返回其他两列?

SELECT c1.customerName
FROM 
    (SELECT cc.customerName, ROUND(SUM(od.priceEach * od.quantityOrdered), 2) as '$ Amount Ordered'
     FROM customers cc
     INNER JOIN orders o ON o.customerNumber = cc.customerNumber
     INNER JOIN orderdetails od ON od.orderNumber = o.orderNumber
     GROUP BY cc.customerName
    ) c1
 INNER JOIN
    (SELECT c.customerName, ROUND(SUM(p.amount), 2) as 'Total $ Amount Paid'
     FROM customers c
     INNER JOIN payments p ON p.customerNumber = c.customerNumber
     GROUP BY c.customerName
    ) c2
WHERE c1.customerName = c2.customerName
GROUP BY c1.customerName
ORDER BY c1.customerName;

2 个答案:

答案 0 :(得分:2)

这应该选择其他列

SELECT c1.customerName, c1.Amount_Ordered as '$ Amount Ordered', c2.Total_Amount_Paid  as 'Total $ Amount Paid'
FROM 
    (SELECT cc.customerName, ROUND(SUM(od.priceEach * od.quantityOrdered), 2) as Amount_Ordered
     FROM customers cc
     INNER JOIN orders o ON o.customerNumber = cc.customerNumber
     INNER JOIN orderdetails od ON od.orderNumber = o.orderNumber
     GROUP BY cc.customerName
    ) c1
 INNER JOIN
    (SELECT c.customerName, ROUND(SUM(p.amount), 2) as  Total_Amount_Paid
     FROM customers c
     INNER JOIN payments p ON p.customerNumber = c.customerNumber
     GROUP BY c.customerName
    ) c2
WHERE c1.customerName = c2.customerName
GROUP BY c1.customerName
ORDER BY c1.customerName;

答案 1 :(得分:1)

只需将它们添加到选择部分:

SELECT c1.customerName, C1.amountOrdered, C2.amountPaid FROM ...

还有一个建议 - 不要在你的专栏名称中使用空白或像$这样的特殊标志,这是不好的做法。我认为mySql甚至允许它是一个错误