当NEW.status = true时,是否可以在其他行设置'status'为false?

问题描述 投票:0回答:1

我有一个AFTER UPDATE TRIGGER,我只想让一条记录具有以下功能 status 是真实的。这是我的触发器。

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

先谢谢你,对不起,我的语言不好。

mysql sql sql-update database-trigger
1个回答
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 表达式来更新新记录的状态并重置之前的记录(如果有的话)。


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。

这里的 "4 "是指你想改变的ID。 是一个db<>提琴。

© www.soinside.com 2019 - 2024. All rights reserved.