您的位置:首页 > 数据库 > MySQL

REPLACE INTO 与 INSERT ... ON DUPLICATE KEY UPDATE

2014-03-20 16:53 477 查看
效率上来说, INSERT ... ON DUPLICATE KEY UPDATE 比replace 要好, 毕竟replace如果重复则 先删除再插入. 而且replace还有副作用: 1. replace每次要重新分配自增id; 2. replace中执行delete时, 在有外键的情况下会很麻烦; 3. 如果delete时定义的有触发器, 则会被执行; 4. 副作用也会被传播到replica slave.

但是这两个怎么也比你之前的效率高, 想想也知道, 你之前, 先select, 在程序里做判断, 然后再做一个数据库操作.


更新

ON DUPLICATE KEY UPDATE 不会改变自增id;
更新多个列, 简单, 就是on duplicate key update col1=7, col2=8;

实验:

mysql> create table rep_vs_up(id int primary key auto_increment, a int unique, b int, c int, d int );

Query OK, 0 rows affected (0.09 sec)

mysql> insert into rep_vs_up(a,b,c,d) values(1,2,3,4);

Query OK, 1 row affected (0.01 sec)

mysql> select * from rep_vs_up;

+----+------+------+------+------+

| id | a    | b    | c    | d    |

+----+------+------+------+------+

|  1 |    1 |    2 |    3 |    4 |

+----+------+------+------+------+

1 row in set (0.00 sec)

mysql> replace into rep_vs_up (a,b,c) values(1,3,4);

Query OK, 2 rows affected (0.01 sec)

mysql> select * from rep_vs_up;

+----+------+------+------+------+

| id | a    | b    | c    | d    |

+----+------+------+------+------+

|  2 |    1 |    3 |    4 | NULL |

+----+------+------+------+------+

1 row in set (0.00 sec)

mysql> insert into rep_vs_up (a, b, c, d) values(1,6,7,8) on duplicate key update c=7, d=8;

Query OK, 2 rows affected (0.01 sec)

mysql> select * from rep_vs_up;

+----+------+------+------+------+

| id | a    | b    | c    | d    |

+----+------+------+------+------+

|  2 |    1 |    3 |    7 |    8 |

+----+------+------+------+------+

1 row in set (0.00 sec)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐