MySQL 5更新后触发器不起作用

时间:2011-10-09 21:33:54

标签: mysql triggers

知道如何让test_trigger工作吗?

Create table test (
    book_id Int UNSIGNED NOT NULL,
    book_views Int UNSIGNED NOT NULL DEFAULT 0,
Primary Key (book_id)) ENGINE = InnoDB;

Create table trigger_test (
    book_id Int UNSIGNED NOT NULL,
    book_views Int UNSIGNED NOT NULL DEFAULT 0,
Primary Key (book_id)) ENGINE = Memory;

delimiter $$
CREATE TRIGGER test_trigger
   AFTER UPDATE ON test
   FOR EACH ROW
   BEGIN
     DECLARE rows_count INT;
     SELECT count(1) FROM trigger_test WHERE book_id=NEW.book_id INTO @rows_count;

     IF @rows_count = 0 THEN
         INSERT INTO trigger_test(book_id, book_views)
         SELECT book_id, book_views FROM test where book_id = NEW.book_id;
     ELSE
         UPDATE trigger_test
         SET book_views = NEW.book_views
         WHERE book_id = NEW.book_id;
     END IF;
   END$$
delimiter ;

插入/更新无效。以下代码应在trigger_test中插入行,但不插入行。

insert into test values (1, 10);

2 个答案:

答案 0 :(得分:1)

无需参考表'test'。只需使用像这样的新表

INSERT INTO trigger_test(book_id,book_views)
VALUES (NEW.book_id,NEW.book_views); 

您也可以使用Replace语句。

MySQL Replace Syntax

  

REPLACE的工作原理与INSERT完全相同,只是如果表中的旧行与PRIMARY KEY或UNIQUE索引的新行具有相同的值,则在插入新行之前删除旧行。

答案 1 :(得分:0)

触发器是'AFTER UPDATE'触发器...... 在INSERT语句之后不会执行它。

您正在寻找的是更有可能在桌面测试中使用“AFTER INSERT”触发器。