我在 MySQL
数据库中有以下三个 (InnoDB-) 表:
Entity (DLID)
Category (CatID, CatName)
hasCategory (DLID, CatID)
现在,在插入表 hasCategory
后,我想确保每个 Entity
都与至少一个 Category
相关联。因此,我编写了以下触发器:
delimiter |
create trigger Max before insert on hasCategory for each row begin
if (exists (select distinct DLID from Entity where not exists (select distinct new.DLID from new))) then
signal sqlstate '45000'
set message_text = 'Min of 1 category per entity required';
end if;
end|
delimiter ;
现在,当我执行以下查询时:insert into hasCategory values (1, 1);
我得到错误 error code 1146: table mydb.new does not exist
。我创建了一些与此类似的其他触发器,也指的是新表,它在其中运行良好。然而,我不明白是什么导致了这个特定触发器的错误。
select
语句是否可能引起一些麻烦?我读到只有 select into
语句在过程中有效,但我不知道这是否与此有关。
感谢您的帮助!
最佳答案
select distinct new.DLID from new
与错误状态一样,您的数据库中没有表 new
。您可以将 NEW
用于将插入到触发器中的记录,但不能将其用作表名并从中进行选择。
尝试
if (select 1 from Entity where DLID = new.DLID) = 1 then
关于在触发器中引用时,MySQL 表 .new 应该不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13384391/