在MySQL中进行条件插入数据时,可能会用到以下语句,现小结一下。我们先建一个简单的表来作为测试:

CREATE TABLE `books` (


  `id` INT(11) NOT NULL AUTO_INCREMENT,


  `name` VARCHAR(200) NOT NULL,


  PRIMARY KEY (`id`),


  UNIQUE KEY `NewIndex1` (`name`)


) ENGINE=InnoDB DEFAULT CHARSET=utf8;


1.insert ignore into


当插入数据时,如出现错误时,如重复数据,将不返回错误,只以警告形式返回。所以使用ignore请确保语句本身没有问题,否则也会被忽略掉。例如:


INSERT IGNORE INTO books (name) VALUES ('MySQL Manual')


2.on duplicate key update


当primary或者unique重复时,则执行update语句,在原有记录基础上,更新指定字段内容,其它字段内容保留。如update后为无用语句,如id=id,则同1功能相同,但错误不会被忽略掉。例如,为了实现name重复的数据插入不报错,可使用一下语句:


INSERT INTO books (name) VALUES ('MySQL Manual') ON duplicate KEY UPDATE id = id


3.insert … select … where not exist


根据select的条件判断是否插入,可以不光通过primary 和unique来判断,也可通过其它条件。例如:


INSERT INTO books (name) SELECT 'MySQL Manual' FROM dual WHERE NOT EXISTS (SELECT id FROM books WHERE id = 1)


4.replace into


如果存在primary or unique相同的记录,则先删除掉。再插入新记录。如果记录有多个字段,在插入的时候如果有的字段没有赋值,那么新插入的记录这些字段为空。


REPLACE INTO books SELECT 1, 'MySQL Manual' FROM books




进一步测试用例:

CREATE TABLE `books` (

  `id` INT(11) NOT NULL AUTO_INCREMENT,

  `name` VARCHAR(200) NOT NULL,

  `author` VARCHAR(200) NOT NULL,

  PRIMARY KEY (`id`),

  UNIQUE KEY `NewIndex1` (`name`)

) ENGINE=INNODB DEFAULT CHARSET=utf8;


INSERT IGNORE INTO books (NAME,author) VALUES ('MySQL Manual','aaa');


INSERT INTO books (NAME,author) VALUES ('MySQL Manual','bbbb') ON DUPLICATE KEY UPDATE id = id+1;

INSERT INTO books (id,NAME,author) VALUES (1,'MySQL Manual','bbbb') ON DUPLICATE KEY UPDATE id = id+1;

INSERT INTO books (id,NAME,author) VALUES (1,'MySQL Manualaaaa','bbbb') ON DUPLICATE KEY UPDATE id = id+1;


REPLACE INTO books SELECT 1, 'MySQL Manual','cccc' FROM books;

REPLACE INTO books (NAME,author) SELECT 'MySQL Manual','ddddd' FROM books;



http://blog.163.com/wunan_23/blog/static/19556232020125212382924/

http://blog.csdn.net/jbboy/article/details/46828917

http://blog.163.com/wunan_23/blog/static/19556232020125212321897/