檢查是否存在 MySQL 條目,如果存在,如何覆蓋其他列?


為此,請使用 INSERT ON DUPLICATE KEY UPDATE 命令。我們首先建立一個表 -

mysql> create table DemoTable1891
   (
   FirstName varchar(20),
   UNIQUE KEY(FirstName)
   );
Query OK, 0 rows affected (0.00 sec)

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

mysql> insert into DemoTable1891 values('Chris') on duplicate key update  FirstName='Robert';
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1891 values('David') on duplicate key update  FirstName='Robert';
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1891 values('Chris') on duplicate key update  FirstName='Robert';
Query OK, 2 rows affected (0.00 sec)

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

mysql> select * from DemoTable1891;

這將產生以下輸出 -

+-----------+
| FirstName |
+-----------+
| David     |
| Robert    |
+-----------+
2 rows in set (0.00 sec)

更新日期:2019 年 12 月 27 日

216 次瀏覽

職業生涯啟航

透過完成課程獲取認證

開始學習
廣告