MySQL 5 更新后触发器不起作用
知道如何让 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);
Any idea how to get test_trigger working?
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 ;
Insert/update is not working. Following code should insert row in trigger_test but its not inserting row.
insert into test values (1, 10);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无需引用表“测试”。只需使用这样的 NEW 表
也可以使用 Replace 语句。
MySQL 替换语法
There is no need to reference the table 'test'. Just use the NEW table like this
Also you could use the Replace statement.
MySQL Replace Syntax
该触发器是“更新后”触发器...
它不会在 INSERT 语句之后执行。
您正在寻找的更有可能在表测试中使用“AFTER INSERT”触发器。
The trigger is an 'AFTER UPDATE' trigger ...
It won't be executed after an INSERT statement.
What you are looking for is more likely to use an 'AFTER INSERT' trigger on table test.