溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

mysql中insert?ignore、insert和replace的區(qū)別是什么

發(fā)布時(shí)間:2022-08-25 13:48:46 來源:億速云 閱讀:188 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“mysql中insert ignore、insert和replace的區(qū)別是什么”的相關(guān)知識,小編通過實(shí)際案例向大家展示操作過程,操作方法簡單快捷,實(shí)用性強(qiáng),希望這篇“mysql中insert ignore、insert和replace的區(qū)別是什么”文章能幫助大家解決問題。

insert ignore、insert和replace的區(qū)別

指令已存在不存在舉例
insert報(bào)錯(cuò)插入insert into names(name, age) values(“小明”, 23);
insert ignore忽略插入insert ignore into names(name, age) values(“小明”, 24);
replace替換插入replace into names(name, age) values(“小明”, 25);

表要求:有PrimaryKey,或者unique索引

結(jié)果:表id都會自增

測試代碼

創(chuàng)建表

CREATE TABLE names(
    id INT(10) PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) UNIQUE,
    age INT(10)
)

插入數(shù)據(jù)

mysql> insert into names(name, age) values("小明", 24);
mysql> insert into names(name, age) values("大紅", 24);
mysql> insert into names(name, age) values("大壯", 24);
mysql> insert into names(name, age) values("秀英", 24);

mysql> select * from names;
+----+--------+------+
| id | name   | age  |
+----+--------+------+
|  1 | 小明   |   24 |
|  2 | 大紅   |   24 |
|  3 | 大壯   |   24 |
|  4 | 秀英   |   24 |
+----+--------+------+

insert

插入已存在, id會自增,但是插入不成功,會報(bào)錯(cuò)

mysql> insert into names(name, age) values("小明", 23);

ERROR 1062 (23000): Duplicate entry '小明' for key 'name'

replace

已存在替換,刪除原來的記錄,添加新的記錄

mysql> replace into names(name, age) values("小明", 23);
Query OK, 2 rows affected (0.00 sec)

mysql> select * from names;
+----+--------+------+
| id | name   | age  |
+----+--------+------+
|  2 | 大紅   |   24 |
|  3 | 大壯   |   24 |
|  4 | 秀英   |   24 |
|  6 | 小明   |   23 |
+----+--------+------+

不存在替換,添加新的記錄

mysql> replace into names(name, age) values("大名", 23);
Query OK, 1 row affected (0.00 sec)

mysql> select * from names;
+----+--------+------+
| id | name   | age  |
+----+--------+------+
|  2 | 大紅   |   24 |
|  3 | 大壯   |   24 |
|  4 | 秀英   |   24 |
|  6 | 小明   |   23 |
|  7 | 大名   |   23 |
+----+--------+------+

insert ignore

插入已存在,忽略新插入的記錄,id會自增,不會報(bào)錯(cuò)

mysql> insert ignore into names(name, age) values("大壯", 25);
Query OK, 0 rows affected, 1 warning (0.00 sec)

插入不存在,添加新的記錄 

mysql> insert ignore into names(name, age) values("壯壯", 25);
Query OK, 1 row affected (0.01 sec)

mysql> select * from  names;
+----+--------+------+
| id | name   | age  |
+----+--------+------+
|  2 | 大紅   |   24 |
|  3 | 大壯   |   24 |
|  4 | 秀英   |   24 |
|  6 | 小明   |   23 |
|  7 | 大名   |   23 |
| 10 | 壯壯   |   25 |
+----+--------+------+

關(guān)于“mysql中insert ignore、insert和replace的區(qū)別是什么”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點(diǎn)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI