insert ignore无法阻止重复插入

时间:2013-07-15 16:48:50

标签: mysql

我从表students中选择数据并将其插入tests表中,如

 CREATE TABLE tests(
  `student_id` int NOT NULL,
  `student_iden_number` varchar(255) NOT NULL DEFAULT '000000',
  `student_names` varchar(255) NOT NULL DEFAULT  'jane doe'
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

我正在使用此代码

insert ignore into tests (student_id,student_iden_number,student_names) select student_id,student_iden_number,student_names from students;

但是,如果我运行插入忽略代码两次,则插入重复记录。这是我的students

CREATE TABLE `students` (
`student_id` INT NOT NULL AUTO_INCREMENT,
`student_iden_number` varchar(255) NOT NULL DEFAULT '000000',
`student_names` varchar(255) NOT NULL DEFAULT  'jane doe',
`student_gender` ENUM('female', 'male') DEFAULT  'female',
`student_guardian_names` varchar(255) NOT NULL DEFAULT  'the guardian',
`student_guardian_telephone` varchar(255) NOT NULL DEFAULT '0000000',
`student_date_of_birth` DATE DEFAULT  '00-00-0000',
`student_date_entered` DATE DEFAULT  '00-00-0000',
`student_date_left` DATE DEFAULT  '00-00-0000',
`student_current_status` ENUM('in-session', 'suspended', 'expelled-for-good', 'at-home-sick', 'cleared' ,'other') DEFAULT  'other',
`student_profile` varchar(255) DEFAULT  'lorem ipsum',
`student_picture` varchar(255) NOT NULL DEFAULT 'placeholder.png',
`student_has_a_medical_condition` ENUM('no', 'yes') DEFAULT  'no',
`student_name_of_condition` varchar(255) NOT NULL DEFAULT 'none',
`student_current_home_address` varchar(255) NOT NULL DEFAULT  'home address',
`student_current_home_latitude` varchar(255) NOT NULL DEFAULT  '0000-00-000',
PRIMARY KEY (`student_id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

为什么要插入重复数据而不是忽略它?

1 个答案:

答案 0 :(得分:5)

您的tests表格上没有任何主键或唯一键,因此您插入的任何内容都不会被视为重复。 ignore仅在尝试插入会导致重复密钥冲突的行时发挥作用。

相关问题