子查询在select语句

时间:2016-10-30 10:55:40

标签: mysql sql database

假设我有两个表,orderdetails和order。

我想打印orderDate,订单的状态&总价。

在orderdetails表中,有orderNumber,quantityOrdered,priceEach& PRODUCTCODE。

在订单中,有状态& ORDERNUMBER。

我已尝试过此代码,但无效。

SELECT orderDate, status,  (SELECT SUM(quantityOrdered * priceEach) AS prices FROM orderdetails GROUP BY orderNumber)

FROM orders o, orderdetails od

WHERE od.orderNumber = o.orderNumber

3 个答案:

答案 0 :(得分:4)

使用联接:

SELECT t1.orderDate,
       t1.status,
       t2.prices
FROM orders t1
INNER JOIN
(
    SELECT orderNumber,
           SUM(quantityOrdered * priceEach) AS prices
    FROM orderdetails
    GROUP BY orderNumber
) t2
    ON t1.orderNumber = t2.orderNumber

答案 1 :(得分:1)

你的方法是合理的。但它应该是这样的:

SELECT o.orderDate, o.status,
       (SELECT SUM(od.quantityOrdered * od.priceEach)
        FROM orderdetails ol
        WHERE od.orderNumber = o.orderNumber
       ) as Prices
FROM orders o;

这称为相关子查询。请注意WHERE子句而不是GROUP BY

答案 2 :(得分:0)

您可以执行如下所示的简单连接

SELECT
    o.date AS order_date,
    o.status AS order_status,
    SUM(od.quanityordered * od.price) AS total_price
FROM orderdetails od
INNER JOIN order o
ON o.ordernumber = od.ordernumber
GROUP BY order_date, order_status