正确的 MySQL INSERT ... ON DUPLICATE KEY 语法?
mysqlmysqli database
语法如下 −
insert into yourTableName values(yourValue1,yourValue2,..N) on duplicate key update yourColumnName1=yourValue1,yourColumnName2=yourValue2,....N;
首先我们创建一个表 −
mysql> create table DemoTable1539 -> ( -> EmployeeName varchar(20), -> EmployeeSalary int, -> UNIQUE KEY(EmployeeName) -> ); Query OK, 0 rows affected (0.62 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1539 values('Chris',4500) on duplicate key update EmployeeName='Robert',EmployeeSalary=8500; Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable1539 values('David',5500) on duplicate key update EmployeeName='Robert',EmployeeSalary=8500; Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1539 values('Chris',4500) on duplicate key update EmployeeName='Robert',EmployeeSalary=8500; Query OK, 2 rows affected (0.14 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1539;
这将产生以下输出 −
+--------------+----------------+ | EmployeeName | EmployeeSalary | +--------------+----------------+ | Robert | 8500 | | David | 5500 | +--------------+----------------+ 2 rows in set (0.00 sec)