使用MySql插入当前表时触发更新另一个表?

时间:2012-11-21 10:46:42

标签: mysql triggers

我不擅长数据库中的触发器

触发器:

delimiter $$

    CREATE
    DEFINER=`root`@`localhost`
    TRIGGER `bon_apetite`.`orders_insert_update_trigger`
    AFTER INSERT ON `bon_apetite`.`orders`
    FOR EACH ROW
    BEGIN
    update budget_tracking set new.monthly_balance = old.monthly_balance + new.total_price
    where tracking_userid = new.order_userid;
    END
    $$

表:

budget_tracking和订单

列:

budget_tracking(id,budget_userid,monthly_balance,created_date,modified_date)

订单(ORDER_ID,order_userid,TOTAL_PRICE,CREATED_DATE,MODIFIED_DATE)

budget_userid和order_userid是另一个表中主键的外键。

我想要的只是当我向订单表插入值时,触发器应该更新budget_tracking表的monthly_balance字段以及两个表的created_date和modified_date。

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

试试这个

BEGIN
update budget_tracking set monthly_balance = monthly_balance + new.total_price
where tracking_userid = new.order_userid;
END

答案 1 :(得分:1)

试试这个:

DELIMITER $$

CREATE DEFINER=`root`@`localhost` TRIGGER `bon_apetite`.`orders_insert_update_trigger` AFTER INSERT ON `bon_apetite`.`orders` FOR EACH ROW
BEGIN
UPDATE budget_tracking SET monthly_balance = monthly_balance + new.total_price
WHERE tracking_userid = new.order_userid;
END$$

DELIMITER ;