基于select的MySQL更新

时间:2011-11-18 06:58:16

标签: mysql select sql-update

SELECT 
   table_1.id, 
   (SELECT SUM(amount) FROM table_2 WHERE table_1.id = table_2.bid) AS sum_total 
FROM table_1 
WHERE table_1.total!=0

我需要更新table_1.total,以使其与sum_total相等。

任何adivce?

3 个答案:

答案 0 :(得分:2)

这个简单的查询应该可以很好地工作。

UPDATE 
   table_1 
SET 
   table_1.total = (SELECT SUM(amount) FROM table_2 WHERE table_1.id = table_2.bid) 
WHERE table_1.total!=0;

答案 1 :(得分:1)

这适合你吗?

UPDATE table_1 set total = (SELECT SUM(amount) FROM table_1 WHERE table_1.id = table_1.bid) AS sum_total)

答案 2 :(得分:1)

尝试以下:

update table_1 as t1 left join (select SUM(amount) as totalamount ,id FROM table_1 group by id) as t2 on t1.id =t2.id 
 set  t1.total=t2.totalamount 

请做一些必要的修改。