在 MySQL 中,哪個技術更有效率地替換重複記錄?


為了替換重複記錄並且避免在插入時出現任何錯誤,請使用 INSERT ON DUPLICATE KEY UPDATE。我們首先建立一個數據表 −

mysql> create table DemoTable
   -> (
   -> Id int,
   -> Name varchar(20),
   -> UNIQUE(Id,Name)
   -> );
Query OK, 0 rows affected (0.78 sec)

使用 insert 命令在表中插入一些記錄 −

mysql> insert into DemoTable values(101,'Chris') on duplicate key update Id=10001,Name='Robert';
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(102,'Mike') on duplicate key update Id=10001,Name='Robert';
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(101,'Chris') on duplicate key update Id=10001,Name='Robert';
Query OK, 2 rows affected (0.10 sec)

使用 select 語句顯示錶中的所有記錄 −

mysql> select *from DemoTable;

這會生成以下輸出 −

+-------+--------+
|    Id | Name   |
+-------+--------+
|   102 | Mike   |
| 10001 | Robert |
+-------+--------+
2 rows in set (0.00 sec)

更新於: 13-Dec-2019

69 瀏覽量

開始您的 職業

透過完成本課程,獲得認證

開始
廣告
© . All rights reserved.