我想在Mysql中创建一个触发器。 在 Insert 之前和 Update 之前,仅在 ID 存在于另一个表中时插入值。
这是我的触发器(插入之前),它不起作用:
DELIMITER $$
CREATE TRIGGER
`before_insert_id`
BEFORE INSERT ON
`table2`
FOR EACH ROW
BEGIN
DECLARE msg VARCHAR(255);
IF NEW.id =
( SELECT id
FROM table2
WHERE NEW.id not in (select id from table1)
)
THEN
SET msg = 'id not in table1';
SIGNAL SQLSTATE '45002' SET message_text = msg ;
END IF ;
END ;
$$
DELIMITER ;
我们还应该在 if 语句通过后在 table2 中插入值吗?或者只是为了检查?
最佳答案
IF NOT EXISTS (select * from table1 where id = new.id) then set msg = 'id not in table1' signal... end if;如果存在,则会自动插入数据。
关于mysql - 插入前创建触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56117005/