【问题标题】:update table in batches using store procedure使用存储过程批量更新表
【发布时间】:2014-03-12 11:08:07
【问题描述】:

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

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 记录更新完整的表

【问题讨论】:

    标签: php mysql sql mysql-workbench


    【解决方案1】:

    LIMIT 可以与UPDATE 一起使用,但只能与row count 一起使用

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

    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 //
    

    【讨论】:

    • 感谢您的回答,但测试是我来自星型模式的事实表,因此我没有主键
    • @Developer 请参考dev.mysql.com/doc/refman/5.0/en/update.html。明确规定**对于多表语法,不能使用ORDER BY和LIMIT**。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 2011-05-02
    相关资源
    最近更新 更多