MySQL触发器不起作用

时间:2018-08-09 23:27:13

标签: mysql select triggers sql-update declare

我有3张桌子

tbl_payments(pay_id,date,amount,description,-------)
tbl_pay_trans(pay_id,trans_id)
tbl_transactions(trans_id,trans_date,trans_amount,trans_description,-----)

'tbl_transaction'具有来自'tbl_payments'的相同数据以及一些其他值。为了维护两个表之间的关系,我使用了“ tbl_pay_trans”。我想做的是,当对tbl_payments(amount,description)完成更新时,需要在tbl_transactions(trans_amount,trans_description)中进行相同的更改。我编写了一个触发器来做到这一点,但是它没有像预期的那样更新tbl_transaction表的值。

我的触发器是

DELIMITER $$
CREATE TRIGGER update_trans 
    AFTER UPDATE on tbl_payments
    FOR EACH ROW
BEGIN
    DECLARE new_amount VARCHAR(50);
    DECLARE new_description TEXT;
    DECLARE new_pay_id,new_trans_id INT;

    SET new_pay_id = OLD.pay_id;
    SET new_amount = OLD.amount;
    SET new_description = OLD.description;
    SELECT trans_id INTO new_trans_id FROM tbl_pay_trans WHERE pay_id = new_pay_id;

    UPDATE tbl_transactions SET 
    trans_amount = new_amount,
    trans_description = new_description
    WHERE trans_id = new_trans_id;
END$$
DELIMITER ;

请有人帮助我找出我做错了什么。

1 个答案:

答案 0 :(得分:0)

它不会更新,因为您在OLDamount列上使用description,而您需要使用NEW,即

SET new_amount = NEW.amount;
SET new_description = NEW.description;

OLD指的是之前tbl_payments中发生更新的列值。参见manual