Home > 数据库 > On duplicate key update

On duplicate key update

February 28th, 2011

mysql> create table t1(f1 int,f2 int,f3 int) ;
Query OK, 0 rows affected (0.05 sec)

mysql> desc t1;
+——-+———+——+—–+———+——-+
| Field | Type | Null | Key | Default | Extra |
+——-+———+——+—–+———+——-+
| f1 | int(11) | YES | | NULL | |
| f2 | int(11) | YES | | NULL | |
| f3 | int(11) | YES | | NULL | |
+——-+———+——+—–+———+——-+
3 rows in set (0.00 sec)

mysql>
mysql> alter table t1 add constraint pk_f1 primary key(f1) ;
Query OK, 0 rows affected (0.05 sec)
Records: 0 Duplicates: 0 Warnings: 0

m
mysql>
mysql> insert into t1 values(1,2,3) ;
Query OK, 1 row affected (0.01 sec)

mysql> insert into t1 values(1,2,3) ;
ERROR 1062 (23000): Duplicate entry ’1′ for key ‘PRIMARY’
mysql>
mysql>
mysql>
mysql> select * from t1;
+—-+——+——+
| f1 | f2 | f3 |
+—-+——+——+
| 1 | 2 | 3 |
+—-+——+——+
1 row in set (0.10 sec)

mysql>
mysql> insert into t1 values(1,2,3)
-> on duplicate key update f3=f3+1 ;
Query OK, 2 rows affected (0.01 sec)

mysql> select * from t1;
+—-+——+——+
| f1 | f2 | f3 |
+—-+——+——+
| 1 | 2 | 4 |
+—-+——+——+
1 row in set (0.00 sec)

mysql>
mysql> insert into t1 values(1,2,3) on duplicate key update f3=f3-1,f2=f2+1 ;
Query OK, 2 rows affected (0.01 sec)

mysql> select * from t1;
+—-+——+——+
| f1 | f2 | f3 |
+—-+——+——+
| 1 | 3 | 3 |
+—-+——+——+
1 row in set (0.00 sec)

mysql> insert into t1 values(2,2,3) on duplicate key update f3=f3+1,f2=f2+1 ;
Query OK, 1 row affected (0.00 sec)

mysql> select * from t1;
+—-+——+——+
| f1 | f2 | f3 |
+—-+——+——+
| 1 | 3 | 3 |
| 2 | 2 | 3 |
+—-+——+——+
2 rows in set (0.00 sec)

mysql> select version();
+————+
| version() |
+————+
| 5.1.50-log |
+————+
1 row in set (0.00 sec)

数据库

  1. No comments yet.
  1. No trackbacks yet.