【问题标题】:Trigger MySql Insert Or Update触发 MySql 插入或更新
【发布时间】:2016-06-21 11:29:03
【问题描述】:

插入或更新表后我需要一个 mysql 触发器,我想添加到表通知中(以及将来发送电子邮件通知)

触发器插入工作正常 触发器更新有问题,如果我编辑“单词”他插入正确,但如果我再次编辑...我收到一个错误,因为我尝试在表通知中插入相同的 id

    table_real
    -------------
    | id | word | news |
    -------------
    | 1  | this | this |
    -------------
    | 2  | that | this |
    -------------
    | 3  | this | this |
    -------------

    tablenotifications
    ---------------------
    | id | word | news |
    ---------------------
    | 1  | this |   2   |
    ---------------------
    | 2  | that |   1   |


DELIMITER $$
CREATE
    TRIGGER `trigger_insert` AFTER INSERT
    ON `table_real` 
    FOR EACH ROW BEGIN
        INSERT INTO tablenotifications(id, word, news) VALUES (new.id, new.word, new.news);

    END$$

DELIMITER ;


DELIMITER $$
CREATE
    TRIGGER `trigger_update` AFTER UPDATE 
    ON `table_real` 
    FOR EACH ROW BEGIN

        INSERT INTO tablenotifications (id, word, news) VALUES (new.id, new.word, new.news);

    END$$

DELIMITER ;

解决方案: 编辑表格,更改我的主键

【问题讨论】:

  • 我猜你不应该使用id作为tablenotification中的主键,如果你想将id多次插入到该表中,因为@987654326的主键id @ 表示您只能将id 插入一次到tablenotification。只需使用另一个(自动增量)id 作为该表中的主键。
  • 我改了主键,问题解决了!谢谢

标签: mysql triggers


【解决方案1】:

当引用一个表时,而不是插入,更新与编辑的 id 对应的行。

DELIMITER $$
CREATE
TRIGGER `trigger_update` AFTER UPDATE 
ON `table_real` 
FOR EACH ROW BEGIN

    UPDATE  tablenotifications SET id=new.id,  word=new.word, news=new.news;

END$$

【讨论】:

    猜你喜欢
    • 2016-10-13
    • 1970-01-01
    • 2013-04-05
    • 2018-02-20
    • 1970-01-01
    • 2014-07-10
    • 2013-01-24
    相关资源
    最近更新 更多