在触发器中引用时,MySQL表.new可能不存在

时间:2012-11-14 17:52:38

标签: mysql triggers

我在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语句在程序中有效,但我不知道这是否与此有关。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

select distinct new.DLID from new

正如错误所述,数据库中没有表new。您可以使用NEW作为将插入触发器的记录,但不能将其用作表名并从中进行选择。

if (select 1 from Entity where DLID = new.DLID) = 1 then