错误:<table_name>指定两次,两者都作为&#39; UPDATE&#39;的目标。并作为单独的数据来源

时间:2017-04-06 10:36:04

标签: mysql sql xampp erd

enter image description here

我想更新tot_sales属性 tot_sales为销售员处理的所有订单的order_price&之和

我写了这个更新查询。但它给出了错误

  

#1093 - 表&#39;推销员&#39;被指定两次,两者都作为&#39;更新&#39;的目标。和&gt;作为数据的单独来源

UPDATE salesman
SET salesman.tot_sales = (SELECT SUM(orders.order_price)
                          FROM orders
                          INNER JOIN salesman ON orders.emp_id = salesman.emp_id
                          GROUP BY salesman.emp_id
                          )

1 个答案:

答案 0 :(得分:0)

使用您的方法,使用相关子查询而不是聚合

UPDATE salesman s
    SET s.tot_sales = (SELECT SUM(o.order_price)
                       FROM orders o
                       WHERE o.emp_id = s.emp_id
                      );

这通常写成:

UPDATE salesman s LEFT JOIN
       (SELECT o.emp_id, SUM(o.order_price) as total_price
        FROM orders o
        GROUP BY o.emp_id
       ) o
       ON o.emp_id = s.emp_id
    SET s.tot_sales = o.total_price;