mysql:insert ignore、insert和replace區別

mysql:insert ignore、insert和replace區別 


insert    報錯    插入    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索引
結果:表id都會自增

測試代碼
創建表

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

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會自增,但是插入不成功,會報錯

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 |
+----+--------+------+
1
2
3
4
5
6
7
8
9
10
11
12
不存在替換,添加新的記錄

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會自增,不會報錯

mysql> insert ignore into names(name, age) values("大壯", 25);
Query OK, 0 rows affected, 1 warning (0.00 sec)
1
2
插入不存在,添加新的記錄

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 |
+----+--------+------+

 

-------------------------

更多參考:

https://www.mysqltutorial.org/mysql-insert-ignore/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章