Rumah >pangkalan data >tutorial mysql >Apakah perbezaan antara insert ignore, insert dan replace dalam mysql
指令 | 已存在 | 不存在 | 举例 |
---|---|---|---|
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); |
Keperluan jadual: PrimaryKey, atau indeks unik
Keputusan: id jadual akan dinaikkan
Buat jadual
CREATE TABLE names( id INT(10) PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255) UNIQUE, age INT(10) )
Sisipkan data
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 | +----+--------+------+
Sisipan sudah wujud, id akan ditambah, tetapi jika sisipan tidak berjaya, ralat akan dilaporkan
mysql> insert into names(name, age) values("小明", 23); ERROR 1062 (23000): Duplicate entry '小明' for key 'name'
Penggantian sudah wujud, padam rekod asal, tambah rekod baharu
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 | +----+--------+------+
Tiada penggantian, tambah rekod baharu
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 | +----+--------+------+
Sisipkan sudah wujud, abaikan rekod yang baru dimasukkan, id akan ditambah, tiada ralat akan dilaporkan
mysql> insert ignore into names(name, age) values("大壮", 25); Query OK, 0 rows affected, 1 warning (0.00 sec)
Sisipkan tidak wujud, tambah rekod baru
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 | +----+--------+------+
Atas ialah kandungan terperinci Apakah perbezaan antara insert ignore, insert dan replace dalam mysql. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!