insert into 是插入表最常用的语句,一般我们往表里插入数据要首先判断是否存在,如果不存在则插入,存在的话再update 更改。举个栗子~~~~
if not exists (select 1 from t where id = 1) then
insert into t(id, update_time) values(1, getdate())
else
update t set update_time = getdate() where id = 1
replace into
也是往表里插入数据,它执行的逻辑是,先插入数据,根据表的主键或者索引判断是否有存在数据,无则插入成功,有则替换已存在数据。REPLACE发现重复的先删除再插入,如果记录有多个字段,在插入的时候如果有的字段没有赋值,那么新插入的记录这些字段为空。(增加数据量,更新重复数据用)
但是!如果表是有自增字段的时候,replace into 要慎用,为啥要慎用请复制链接https://blog.xupeng.me/2013/10/11/mysql-replace-into-trap/
replace into
table 1
id name ps
1 tb a
2 zp b
table2
id(主键) name
1 tb
2 cw
3 zp
replace into table1 select * from table2执行结果为
table1
id name ps
1 tb NULL
2 cw NULL
3 zp NULL
insert ignore into 忽略已存在的数据,插入不存在的数据。即表1插入表2,若表1的数据已存在在表2则跳过,插入不存在的数。(增加数据量,不更改重复数据用)
insert into
table 1
id name
1 tb
2 zp
table2
id(主键) name
1 tb
2 cw
3 zp
insert ignore into table1 select * from table2执行结果为
table1
id name
1 tb
2 zp
3 zp