我有以下触发器:
CREATE TRIGGER sum
AFTER INSERT
ON news
FOR EACH ROW
UPDATE news SET NEW.sum = (NEW.int_views + NEW.ext_views)/NEW.pageviews
它汇总了表格的int_views
和ext_views
列,并将其除以总浏览量。
每当我尝试向新闻添加新行时,我都会收到以下错误:
ERROR 1442 (HY000) at line 3: Can't update table 'news' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
触发器对我来说似乎很简单。触发器无法运行是否有原因?
答案 0 :(得分:12)
症状是,您在UPDATE
触发器内运行INSERT
(对于所有行) - 都修改了表,这是不允许的。
也就是说,如果我猜错了你的触发器的意图,你不想更新所有行,而只想更新新插入的行。您可以使用
轻松实现这一目标CREATE TRIGGER sum
BEFORE INSERT
ON news
FOR EACH ROW
SET NEW.sum = (NEW.int_views + NEW.ext_views)/NEW.pageviews
请注意,这是一个BEFORE INSERT
触发器,因为您希望在将行写入表之前更改该行。
答案 1 :(得分:7)
如果您尝试在导致触发触发的同一个表上更新/插入,请不要使用常见的sql
命令,如
-> UPDATE TABLE_NAME SET COLUMN_NAME = VALUE WHERE CONDITION_LIST;
-> INSERT INTO TABLE_NAME VALUES("VALUE1","VALUE2");
这不起作用。仅使用set来指定您更新的列的值。
示例:
CREATE TRIGGER trigger_name BEFORE/AFTER INSERT/UPDATE ON table_name
FOR EACH ROW
SET NEW.COLUMN_NAME = "VALUE";
答案 2 :(得分:0)
我处于类似的状况,必须运行两个触发器:
经过大量的努力,我终于能够通过以下方式编写TRIGGER:
用于更新INSERT上的值
CREATE TRIGGER `INSERT_DISCOUNT_SERVICES` BEFORE INSERT ON `services`
FOR EACH ROW SET
NEW.discount_5_rate = (NEW.ndis_rate*0.05),
NEW.discount_10_rate=(NEW.ndis_rate*0.10),
NEW.discount_15_rate=(NEW.ndis_rate*0.15)
类似地
用于在UPDATE上更新值
CREATE TRIGGER `UPDATE_DISCOUNTS_SERVICES` BEFORE UPDATE ON `services`
FOR EACH ROW SET
NEW.discount_5_rate = (NEW.ndis_rate*0.05),
NEW.discount_10_rate=(NEW.ndis_rate*0.10),
NEW.discount_15_rate=(NEW.ndis_rate*0.15)