2012-12-04 42 views
0

我做了新的觸發器,它必須更新員工的工資。它從表格付款中獲取2個值(現金和月),並將它們分成一列「how_much_to_pay」。無法更新觸發器中的表

我看了一下題目: MySQL triggers cannot update rows in same table the trigger is assigned to. Suggested workaround?

但didin't幫我,因爲他們只用1臺,它們可以把「新」沒有問題。

這裏是我的觸發器:

create trigger pay_out before insert on `payment_out` 
for each row 
then 
UPDATE `payment_out` o 
INNER JOIN payment p ON p.id_1 = o.id_1 AND o.id2 = p.id2 
SET o.`how_much_to_pay` = p.cash/p.months; 
end; 
$$ 

下面是表:

table payment_out 
id1 
id2 
how_much_to_pay 

table payment 
id1 
id2 
cash 
months 

和錯誤本身:

1442 - Can't update table payment_out in stored function/trigger because it is already used by statement which invoked this stored function/trigger. 

回答

1

如果你有一個一對一的關係之間的兩個表,那麼你可以在BEFORE INSERT觸發器中使用這段代碼 -

BEGIN 
    SELECT p.cash, p.months INTO @cash, @months 
    FROM payment p 
    WHERE p.id_1 = NEW.id_1 AND p.id2 = NEW.id2; 

    SET NEW.how_much_to_pay = @cash/@months; 
END 
+0

那麼,這個工作,但「多少錢」是NULL,即使現金= 8000,月= 8。 – trinny

+0

如果p.cash或p.months之一是空值。嘗試從觸發器運行SELECT,將正確的值添加到WHERE條件。結果是什麼? – Devart

+0

當我注意到它時,我將它更改爲0.00。 – trinny