使用来自另一个表的信息更新表并进行修改

时间:2012-12-22 22:13:27

标签: mysql

我想将数据(带有修改)从一个表移动到另一个表。

UPDATE table2 
SET val_new=(SELECT (table1.val_old - SUM(table3.val_2)) as some1 
FROM table3 
INNER JOIN table1 ON table3.id_some=.table1.id_some 
WHERE table3.id_typ<=2 
AND table3.id_status=1 
group by table3.id_some);

我有错误:

Error Code: 1242. Subquery returns more than 1 row

我必须采取哪些措施来纠正此问题?

1 个答案:

答案 0 :(得分:0)

最简单的解决方法是:

UPDATE table2 SET 
val_new=ifnull((
     SELECT (table1.val_old - SUM(table3.val_2)) as some1 
     FROM table3 
     INNER JOIN table1 ON table3.id_some=.table1.id_some 
     WHERE table3.id_typ<=2 
     AND table3.id_status=1 
     WHERE table3.table2_id = table2.id -- ADDED THIS LINE
     group by table3.id_some), val_new);