触发器

时间:2016-08-23 16:22:03

标签: mysql triggers

我试图在插入之前插入具有触发器的一个插入查询插入多行,如果条件为真,则引发重复异常

表格结构

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(50) DEFAULT NULL,
  `last_name` varchar(50) DEFAULT NULL,
  `date_registration` date DEFAULT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(128) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `email` (`email`),
  KEY `date_registration` (`date_registration`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
/*!50100 PARTITION BY RANGE (id)
(PARTITION id1k VALUES LESS THAN (1000) ENGINE = MyISAM,
 PARTITION id3k VALUES LESS THAN (3000) ENGINE = MyISAM,
 PARTITION id7k VALUES LESS THAN (7000) ENGINE = MyISAM,
 PARTITION id10k VALUES LESS THAN (10000) ENGINE = MyISAM,
 PARTITION id13k VALUES LESS THAN (13000) ENGINE = MyISAM,
 .........

触发代码

delimiter //
drop trigger if exists users_before_insert //
create trigger users_before_insert before insert on users
for each row
begin
set @found := false;
select true into @found from users u where u.email = NEW.email;
if @found then
signal sqlstate '23000' set message_text = 'Email alread exists !';
end if;
end   //
delimiter ;

当我尝试插入重复记录时,即使查询使用忽略

EXP:

insert ignore into users (first_name,last_name,date_registration,email,password) values
('aaaa','zzzz','2016-08-20','aaaa@mywebsite.com','strongpwd1'),
('bbbb','yyyy','2016-08-21','bbbb@mywebsite.com','strongpwd2'),
('cccc','xxxx','2016-08-22','aaaa@mywebsite.com','strongpwd3'),
('dddd','wwww','2016-08-23','dddd@mywebsite.com','strongpwd4');

ERROR 1644 (23000): Email alread exists !

当涉及到第一个副本时,qry已中止' aaaa@mywebsite.com'。

是否存在忽略触发器引发的异常的解决方案?

1 个答案:

答案 0 :(得分:0)

不,虽然此触发器处于活动状态,但您无法插入重复的行。
尝试避免触发不是一个好习惯,那么你应该考虑改变触发触发所需的一组条件。