Mysql避免重复插入记录,可使用ignore关键字:
如果有用主键primary key或者唯一索引unique区分了记录的唯一性,当我们无意插入相同数据的时候(主键值或是唯一索引值重复),
insert into table_name(email,phone,user_id) values('test@163','99999','9999');
ERROR 1062 (23000): Duplicate entry 'test@163' for key 'email'
这表明表中已经存在有email为'test@163'的记录(email为唯一索引),此时可以这样插入
insert ignore into table_name(email,phone,user_id) values('test@163','99999','9999'),
这样当有重复记录就会忽略,执行后返回Query OK, 0 rows affected,还有个应用就是复制表,避免重复记录:
insert ignore into table_name1 select name from table_name2;