MySQL 批量插入,如何不插入重复数据
1、insert ignore into
当插入数据时,如出现错误时,如重复数据,将不返回错误,只以警告形式返回。所以使用ignore请确保语句本身没有问题,否则也会被忽略掉=======》INSERT IGNORE INTO user (name) VALUES ('telami')
2、on duplicate key update
当primary或者unique重复时,则执行update语句,如update后为无用语句,如id=id,则同1功能相同,但错误不会被忽略掉=======》INSERT INTO user (name) VALUES ('telami') ON duplicate KEY UPDATE id = id
3、insert … select … where not exist
根据select的条件判断是否插入,可以不光通过primary 和unique来判断,也可通过其它条件========》INSERT INTO user (name) SELECT 'telami' FROM dual WHERE NOT EXISTS (SELECT id FROM user WHERE id = 1)
4、replace into
如果存在primary or unique相同的记录,则先删除掉。再插入新记录========》REPLACE INTO user SELECT 1, 'telami' FROM books