前几天写项目的时候,遇到一个小问题:用户需要用Excel批量导入数据 , 但是里面的值不可重复,如果在插入的时候做全表查询不仅效率低下,而且代码复杂,在这个时候mysql的唯一索引就显的尤为重要.
1.不存在插入,存在则更新
前提:插入数据的字段必须要有UNIQUE索引或primary key索引
添加索引:https://www.cnblogs.com/Anonymity-zhang/p/12667276.html
在我的示例中,将username设置为UNIQUE索引
1.1 on duplicate key update
如果插入的数据会导致UNIQUE 索引或PRIMARY KEY发生冲突/重复,则执行UPDATE语句,例:
1 INSERT INTO userinfo (username,password) 2 VALUES('wangwu','111111') on duplicate key update 3 password='222222'
解释:如果userinfo 表中有username=’wangwu’的数据,则将其密码修改为’222222’
1.2 replace into
如果插入的数据会导致UNIQUE 索引或PRIMARY KEY发生冲突/重复,则先删除旧数据再插入最新的数据,例:
1 REPLACE INTO userinfo (username,password) VALUES ('wangwu','111111') 2 3 解释:如果userinfo表中有username=’wangwu’的数据,则将其删点,重新插入
2.避免重复插入
关键字/句:insert ignore into,如果插入的数据会导致UNIQUE索引或PRIMARY KEY发生冲突/重复,则忽略此次操作/不插入数据,例:
1 INSERT IGNORE INTO userinfo (username,password) VALUES ('wangwu','111111'); 2 3 解释:如果表中含有username=’wangwu’的数据 , 则忽略此次操作
本文引自:https://blog.csdn.net/t894690230/article/details/77996355