我想更新tot_sales属性 tot_sales为销售员处理的所有订单的order_price&之和
我写了这个更新查询。但它给出了错误
#1093 - 表'推销员'被指定两次,两者都作为'更新'的目标。和>作为数据的单独来源
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
)
答案 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;