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

标签 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);

最佳答案

无需引用表“test”。只需使用像这样的新表

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

您也可以使用 Replace 语句。

MySQL Replace Syntax

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.

关于MySQL 5 更新后触发器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7706702/

相关文章:

sql - MySQL 停止触发器中的事件

sql - 应该更新日期不执行的postgres函数

PHP PDO SELECT LIMIT 问题

mysql - 错误121无法创建表

sql - INSERT IF NOT EXISTS 类型函数供我使用而不将列转换为主键?

SQL服务器触发器

postgresql - Postgres 触发器

mysql - 按用户 ID、月份、总和计算统计数据 - 选择列中的月份数

java - hibernate 选择不同的值按一个值排序

mysql - SQL触发器导致错误