使用存储过程批量更新表

时间:2014-03-12 11:08:08

标签: php mysql sql mysql-workbench

想要根据其他表中的值更新表,但我的表大小非常大并且要优化查询我想要以小块更新表但我无法这样做。这是我的剧本:

DROP PROCEDURE IF EXISTS sp;
Delimiter //
create procedure sp()
begin
  DECLARE i INT unsigned DEFAULT 0;

  SET @i =1;
  while i < 10 do
    update  
      test t,
      (SELECT yearweek(c.currency_date) w,
              c.currency _currency, AVG(c.rate) rate
       FROM currency c
       GROUP BY w,_currency) src 

    set 
       t.value = t.value/src.rate,
       t.currencyid = 'EUR'
    where 
          w =(yearweek(t.created - interval 1 week) )  
      and t.currencyid = _currency
    limit 20000;

    set i = i+1;
  end while;        
END //

当我调用存储过程时,我收到错误:

  

更新和限制的使用不正确。

如何避免这种情况并使用批量20000条记录

更新完整表格

1 个答案:

答案 0 :(得分:0)

LIMIT可与UPDATE一起使用,但仅限row count

我改变了你的程序。在这里,您可以使用批量更新。每当i的值增加时,它都会使用i条记录更新20000的倍数

DROP PROCEDURE IF EXISTS sp;
Delimiter //
create procedure sp()
begin
DECLARE i INT unsigned DEFAULT 0;
SET @i =1;
while i < 10 do
update  test t,
(SELECT yearweek(c.currency_date) w,
c.currency _currency, AVG(c.rate) rate
FROM currency c
GROUP BY w,_currency) src 

set 
t.value = t.value/src.rate,
t.currencyid = 'EUR'
where w =(yearweek(t.created - interval 1 week) )  
and t.currencyid = _currency and t.id in (select id from test order by id limit i*20000, 20000);
set i = i+1;
end while;      
END //