0

我有一个更新后触发器,我只想要一个status为 TRUE 的行。这是我的触发器,

CREATE TRIGGER check_true AFTER UPDATE ON table1 FOR EACH ROW
BEGIN
IF (NEW.status = 1) THEN
UPDATE table1 SET status = 0 WHERE id <> NEW.id;
END IF;
END

我尝试status从 1 更改为 0 没有错误。但是当我尝试从 0 更改为 1 时,会出现这样的错误,

Can't update table 'table1' in stored function/trigger because it is already used by statement which invoked this stored function/trigger

提前谢谢,对不起我的语言不好。

4

2 回答 2

0

触发器无法操作触发它的表,因此您想要做的事情无法通过触发器实现。

另一种选择是重新制定您的update查询,以便一次更新所有需要的记录,例如:

update mytable
set status = case when id = :myid then :status else 0 end
where id = :myid or (status = 1 and :status = 1)

在这里,:id:status代表查询参数。

where子句选择与:id参数匹配的记录 - 如果新状态为1,它还选择状态为的现有记录1(应该只有一个)。

然后,该set子句使用case表达式更新新记录的状态并重置之前的记录(如果有)

于 2020-05-14T08:45:44.713 回答
0

首先,在 MySQL 8+ 中,您可以让 MySQL 强制执行唯一性。

alter table table1 add column status_true varchar(255) generated always as
    (case when status then status end);

create unique index unq_table1_status_true on (status_true);

现在,数据库确保了唯一性。

您可以使用单个更新值update

update table1
    set status = not status
    where status or id = 2

“4”是您要更改为活动的 id。

是一个 db<>fiddle。

于 2020-05-14T11:52:41.207 回答