时间:2021-07-01 10:21:17 帮助过:7人阅读
insert ignore into table
保持原记录,忽略新插入的记录
2.替换
replace into table
替换原记录,即先删除原记录,再插入新的记录
insert into table value("xx","xx") ON DUPLICATE KEY UPDATE
其实这个是原本需要执行3条SQL语句(SELECT,INSERT,UPDATE),缩减为1条语句即可完成。
即
IF (SELECT * FROM where 存在) {
UPDATE SET WHERE ;
} else {
INSERT INTO;
}
如:
mysql> insert into Tble values (1,‘xxx‘,‘xxx‘) ON DUPLICATE KEY UPDATE status =‘drain‘;
Query OK, 2 rows affected (0.00 sec)
上面语句伪代码表示即为
if (select * from table where id=1) {
update device set status =‘drain‘ where id=1
} else {
insert into table value (1,‘xxx‘,‘xxx‘)
}
很明显,id=1 是有的,这样就执行update操作
mysql> select * from table;
+-------+--------+-----------+
| id| status | spec_char |
+-------+--------+-----------+
| 1 | drain | yangting |
| 2 | dead | zhong |
+-------+--------+-----------+
2 rows in set (0.00 sec)
sql解决主键冲突
标签:else strong dev sql col span word round int