Trigger to silently ignore/delete duplicate entries on INSERT

谁都会走 提交于 2019-12-01 21:18:36

Before mysql 5.5. it wasn't possible to stop an insert inside a trigger. There where some ugly work arounds but nothing I would recommend. Since 5.5 you can use SIGNAL to do it.

delimiter //
drop trigger if exists aborting_trigger //
create trigger aborting_trigger before insert on t
for each row
begin
  set @found := false;
  select true into @found from t where a=new.a and b=new.b;

  if @found then
    signal sqlstate '45000' set message_text = 'duplicate insert';
    end if;
  end   //

delimiter ;

Add a unique key (A,B) and use INSERT statement with an IGNORE keyword.

From the reference - If you use the IGNORE keyword, errors that occur while executing the INSERT statement are treated as warnings instead.

INSERT Syntax.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!