MySQL - 多个2列,在同一个表中更新

时间:2013-10-09 02:06:37

标签: mysql subquery multiplication

我想通过将total列与tbl_orders列相乘来更新表格quantity中的cost列。

UPDATE `tbl_orders` SET 
   total = (SELECT quantity * cost AS n1 FROM `tbl_orders` WHERE orderid = 167 LIMIT 1) 
WHERE orderid= 167 LIMIT 1

之前我已经完成了子查询更新,但返回的mysql错误是:

  

您无法为更新指定目标表'tbl_orders'   FROM子句

谁能看到我做错了什么?

1 个答案:

答案 0 :(得分:1)

JOIN相反。

UPDATE  tbl_orders a
        INNER JOIN
        (
            SELECT  orderid, quantity * cost totalCost
            FROM    tbl_orders 
            WHERE   orderid = 167
        ) b ON a.orderid = b.orderid
SET     a.total = b.totalCost
WHERE   a.orderid = 167

如果您要更新所有orderid,请删除所有WHERE条款。