1、给表中的不想重复的字段加上主键(primary key)或者唯一键约束(unique key)
比如不想c1字段出现重复数据
a、创建表的时候
CREATE TABLE `t3` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`c1` int(11) DEFAULT NULL,
`c2` varchar(20) DEFAULT NULL,
`c3` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uidx_c1` (`c1`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8
b、修改表的时候
alter table table_name add unique key `new_uk_name` (`c1`);
使用时:
insert ignore into t3 (c1,c2,c3) values(5,'cc',4),(5,'dd',5);
如果修改过程中出现以下错误:
ERROR 1062 (23000): Duplicate entry
有可能是表中已经存在该字段重复的内容,可以考虑清空表(不仅要的情况)或者先将该字段去重。
2、查询表存在的约束
show create table table_name;
删除对应的唯一键约束
alter table table_name drop index 约束名(非字段名);