创建触发器更新SQL表

时间:2018-11-24 06:46:59

标签: mysql database-trigger

我想创建一个触发器来更新表khohang和表Dothan

这是我的SQL:

CREATE TRIGGER trigger_update on dathang
AFTER UPDATE AS
BEGIN
 UPDATE khohang INNER JOIN dathang on khohang.mahang =dathang.mahang
    SET khohang.soluong = khohang.soluong - (SELECT soluong FROM dathang where khohang.mahang = dathang.mahang)
END

1 个答案:

答案 0 :(得分:0)

在表上执行(插入,更新,删除之前/之后)操作时,将发生触发器,因此触发器将在该操作上触发并在相同或不同的表上执行某些操作。 这是触发器的产物

DELIMITER $$

USE `database_name`$$

DROP TRIGGER  `Tigger_name`$$

CREATE 
    TRIGGER `Tigger_name` BEFORE/AFTER INSERT /UPDATE/DELETE ON `Table_1` /* trigger fire from this table*/
    FOR EACH ROW BEGIN
        /* (query) action perform */ 
        update table_2 set field_1="value" where table_2.id=New.field_1; /*New.field_1 is refrance Table_1.field_1. which record effect by action*/
    END;
$$

DELIMITER ;

参考:https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html