0
我triying在具有插入之前推出了触发器的表与一个插入查询,插入多行,提高复本异常,如果条件为真提出插入忽略异常时,通过触发
表结构
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:当谈到第一个重复的 '[email protected]'
insert ignore into users (first_name,last_name,date_registration,email,password) values
('aaaa','zzzz','2016-08-20','[email protected]','strongpwd1'),
('bbbb','yyyy','2016-08-21','[email protected]','strongpwd2'),
('cccc','xxxx','2016-08-22','[email protected]','strongpwd3'),
('dddd','wwww','2016-08-23','[email protected]','strongpwd4');
ERROR 1644 (23000): Email alread exists !
QRY中止。
是否有解决方案来忽略触发器引发的异常?
为什么你使用触发器来模拟'UNIQUE'索引的作用?您正在选择一封电子邮件来检查它是否存在 - 为什么?为什么不放置一个唯一的索引,并使用'INSERT IGNORE'或'ON DUPLICATE KEY UPDATE'?解决问题的方法并不是忽略由触发器触发的'sqlstate',解决方案是使用正确的工具 - 在你的情况下,正确的工具是'email'字段的索引。通过创建一个包含电子邮件散列的字段,它甚至可以变得高效,因此您的表格中始终有一个固定长度的唯一列。那么你的代码只是一个简单的插入,不需要触发器。 –
谢谢@ N.B。对于你的建议:) 但在'email'上使用UNIQUE INDEX的情况下,由于分区规则,我应该给约束添加'id': _A UNIQUE INDEX必须包含表的分区中的所有列_ – TAHIRI
如果使用分区, 好的。然而,问题是 - 为什么你首先使用分区?您是将数据分区到另一个硬盘上还是在同一个硬盘上? –