MySQL replace statement
时间:2007-01-17 来源:gladness
REPLACE是MySQL对SQL标准的扩展,它会插入记录,或者删除记录再插入记录。如果REPLACE使用的主键或者唯一索引列的值在表中能够找到,则删除该记录再插入新的记录,否则只是插入。如果表没有主键或者唯一索引,那么只是插入。
mysql> desc test;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| uid | int(11) | NO | PRI | | |
| uname | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.03 sec)
mysql> select * from test;
+-----+--------+
| uid | uname |
+-----+--------+
| 1 | uname1 |
| 2 | uname2 |
| 3 | uname3 |
+-----+--------+
3 rows in set (0.00 sec)
mysql> replace into test
-> values (3,'me');
Query OK, 2 rows affected (0.01 sec)
mysql> select * from test;
+-----+--------+
| uid | uname |
+-----+--------+
| 1 | uname1 |
| 2 | uname2 |
| 3 | me |
+-----+--------+
3 rows in set (0.00 sec)
REPLACE的实现,是先向表中插入记录,如果主键冲突或者违反唯一约束,那么删除旧的记录,插入新的记录。
mysql> desc test;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| uid | int(11) | NO | PRI | | |
| uname | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.03 sec)
mysql> select * from test;
+-----+--------+
| uid | uname |
+-----+--------+
| 1 | uname1 |
| 2 | uname2 |
| 3 | uname3 |
+-----+--------+
3 rows in set (0.00 sec)
mysql> replace into test
-> values (3,'me');
Query OK, 2 rows affected (0.01 sec)
mysql> select * from test;
+-----+--------+
| uid | uname |
+-----+--------+
| 1 | uname1 |
| 2 | uname2 |
| 3 | me |
+-----+--------+
3 rows in set (0.00 sec)
REPLACE的实现,是先向表中插入记录,如果主键冲突或者违反唯一约束,那么删除旧的记录,插入新的记录。
相关阅读 更多 +