2014-03-12 79 views
0

想要基於來自其他表的值更新表,但我的表大小是非常大的,爲了優化查詢我想更新小表中的表,但我無法這樣做。這裏是我的腳本:批量更新表使用存儲過程

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

當我打電話的存儲過程,收到錯誤:

incorrect usage of update and limit.

我怎樣才能避免這種情況並更新與20000記錄

回答

0

LIMIT批次完整的表可以使用與UPDATErow 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 // 
+0

感謝的答案,但測試是星型模式我的事實表,因此我沒有主鍵 – Developer

+0

@Developer請參考HTTP:/ /dev.mysql.com/doc/refman/5.0/en/update.html。它明確指出**對於多表語法,不能使用ORDER BY和LIMIT **。 – Andolasoft