REPLACE INTO 为什么返回”2 rows affected”

表的结构:

  1. desc urls;
  2. +-------+---------------------+------+-----+---------+-------+
  3. | Field | Type                | Null | Key | Default | Extra |
  4. +-------+---------------------+------+-----+---------+-------+
  5. | id    | bigint(16) unsigned | NO   | PRI | NULL    |       |
  6. | url   | varchar(255)        | NO   |     | NULL    |       |
  7. | md516 | varchar(32)         | NO   | UNI |         |       |
  8. +-------+---------------------+------+-----+---------+-------+
  9. 3 rows in set (0.01 sec)

原有数据:

  1. +----+-----------------------+------------------+
  2. | id | url                   | md516            |
  3. +----+-----------------------+------------------+
  4. |  0 | http://www.162cm.com/ | 49f6f2aaa26c124a |
  5. +----+-----------------------+------------------+
  6. 1 row in set (0.00 sec)

执行的语句:

  1. REPLACE INTO urls (`url`,`md516`,`id`) VALUES ('http://www.162cm.com/','49f6f2aaa26c124a',0);

而执行这条语句的返回是:

  1. Query OK, 2 rows affected (0.00 sec)

为啥呢….看起来数据啥也没变,不是吗?
看文档:http://au2.php.net/mysql_affected_rows:

Returns the number of affected rows on success, and -1 if the last query failed.

If the last query was a DELETE query with no WHERE clause, all of the records will have been deleted from the table but this function will return zero with MySQL versions prior to 4.1.2.

When using UPDATE, MySQL will not update columns where the new value is the same as the old value. This creates the possibility that mysql_affected_rows() may not actually equal the number of rows matched, only the number of rows that were literally affected by the query.

The REPLACE statement first deletes the record with the same primary key and then inserts the new record. This function returns the number of deleted records plus the number of inserted records.


本文由蝌蚪安尼友情赞助.
相关文章
此条目发表在 未分类 分类目录。将固定链接加入收藏夹。

REPLACE INTO 为什么返回”2 rows affected”》有 2 条评论

  1. 小和尚 CHINA Ubuntu Linux Mozilla Firefox 3.0.11 说:

    replace => first delete ,then insert ?

  2. 游客 CHINA Windows XP Internet Explorer 7.0 说:

    如果该primary key 或unique key的记录存在,是先删再插入。否则就是仅有插入。
    换句话说,replace into … values …语句执行后,affected rows 要么是1 要么是2.

发表评论

电子邮件地址不会被公开。 必填项已被标记为 *

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>