利用 REPLACE INTO 來模擬 DELETE 和 INSERT 來新增記錄
你可以使用 REPLACE INTO,其功能類似於 DELETE + INSERT。讓我們首先建立一個表 -
mysql> create table DemoTable ( Id int, FirstName varchar(50) ); Query OK, 0 rows affected (0.60 sec)
以下是建立唯一索引的查詢 -
mysql> alter table DemoTable add unique id_index(Id); Query OK, 0 rows affected (0.41 sec) Records: 0 Duplicates: 0 Warnings: 0
使用 insert 命令向表中插入一些記錄。由於我們添加了重複記錄,所以新記錄會被新增,即用具有相同 Id 的前一條記錄替換它 -
mysql> replace into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.10 sec) mysql> replace into DemoTable values(101,'David'); Query OK, 1 row affected (0.13 sec) mysql> replace into DemoTable values(100,'Bob'); Query OK, 2 rows affected (0.16 sec)
使用 select 語句顯示錶中的所有記錄 -
mysql> select *from DemoTable;
這將產生以下輸出 -
+------+-----------+ | Id | FirstName | +------+-----------+ | 100 | Bob | | 101 | David | +------+-----------+ 2 rows in set (0.00 sec)
廣告