简体   繁体   中英

Update column with a subquery

ALTER TABLE order_t ADD Totalfixed DECIMAL(7,2);

UPDATE Order_t 
    SET Totalfixed = (
        SELECT orderid, SUM(price * quantity) AS tf 
        FROM
            orderline ol,
            product p
        WHERE
            ol.productid = p.productid 
            AND ol.orderid = orderid
        GROUP BY orderid
    );

Everything works fine separately but I get:

operand should contain 1 column

And if I remove orderid from the subquery, I get:

subquery returns more than 1 row

Is there anyway to make this work without a join ?

Regardless of the database, the context requires a scalar subquery. This means avoid the group by and return only one column:

UPDATE Order_t 
    SET Totalfixed = (
        SELECT SUM(price * quantity) AS tf 
        FROM orderline ol JOIN
             product p
             ON ol.productid = p.productid  
        WHERE ol.orderid = Order_t.orderid
     );

I also fixed the JOIN syntax ( always use explicit joins) and the correlation clause so it refers to the outer query.

UPDATE A 
SET Totalfixed = SUM(price * quantity)
FROM Order_t A 
INNER JOIN orderline ol  ON ol.orderid = A.orderid 
INNER JOIN product p  ON ol.productid = p.productid  

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