要替换重复的记录并避免在插入时出现任何错误,请使用INSERT ON DUPLICATE KEY UPDATE。让我们首先创建一个表-
mysql> create table DemoTable -> ( -> Id int, -> Name varchar(20), -> UNIQUE(Id,Name) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values(101,'Chris') on duplicate key update Id=10001,Name='Robert'; mysql> insert into DemoTable values(102,'Mike') on duplicate key update Id=10001,Name='Robert'; mysql> insert into DemoTable values(101,'Chris') on duplicate key update Id=10001,Name='Robert';
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+-------+--------+ | Id | Name | +-------+--------+ | 102 | Mike | | 10001 | Robert | +-------+--------+ 2 rows in set (0.00 sec)