简体   繁体   English

使用子查询更新列

[英]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 操作数应包含1列

And if I remove orderid from the subquery, I get: 而且,如果我从子查询中删除了orderid ,则会得到:

subquery returns more than 1 row 子查询返回1行以上

Is there anyway to make this work without a join ? 无论如何,有没有join就可以使这项工作吗?

Regardless of the database, the context requires a scalar subquery. 无论数据库如何,上下文都需要标量子查询。 This means avoid the group by and return only one column: 这意味着避免group by并且仅返回一列:

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. 我还修复了JOIN语法( 始终使用显式联接)和相关子句,因此它引用了外部查询。

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  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM