2

我正在尝试运行以下语句:

INSERT into table (col1,col2,col3,col4)
    VALUES ('1','2','3','4') 
    ON DUPLICATE KEY UPDATE col3 = '3'

根据论坛中的许多示例,这应该适用于系统中当前的记录,但是当我执行此操作并随后运行选择时,col3 不受影响。运行插入语句时没有错误。有任何想法吗?

4

1 回答 1

0

见下文,创建了一个名为 TAB 的表,在 c3 上具有唯一键。

  1. 第一个插入,它是一个光滑的插入。
  2. 第二次插入,c3 处的值更新为 4,因为我在 c3 上具有唯一键。
  3. 第三次插入,它再次平滑,因为这次它的 (1,2,3,4) 不是重复的,因为表只有 (1,2,4,4)
  4. 第四次插入,被炸了,因为插入值“3”是重复的,当尝试更新时,c3 的更新值“4”也是重复的。

-

mysql> desc tab;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| c1    | int(11) | YES  |     | NULL    |       |
| c2    | int(11) | YES  |     | NULL    |       |
| c3    | int(11) | YES  | UNI | NULL    |       |
| c4    | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
4 rows in set (0.00 sec)

mysql> delete from tab;
Query OK, 2 rows affected (0.06 sec)

mysql> select * from tab;
Empty set (0.00 sec)

mysql> INSERT into tab (c1,c2,c3,c4)     VALUES ('1','2','3','4')      ON DUPLICATE KEY UPDATE c3 = '4';
Query OK, 1 row affected (0.05 sec)

mysql> select * from tab;
+------+------+------+------+
| c1   | c2   | c3   | c4   |
+------+------+------+------+
|    1 |    2 |    3 |    4 |
+------+------+------+------+
1 row in set (0.00 sec)

mysql> INSERT into tab (c1,c2,c3,c4)     VALUES ('1','2','3','4')      ON DUPLICATE KEY UPDATE c3 = '4';
Query OK, 2 rows affected (0.07 sec)

mysql> select * from tab;
+------+------+------+------+
| c1   | c2   | c3   | c4   |
+------+------+------+------+
|    1 |    2 |    4 |    4 |
+------+------+------+------+
1 row in set (0.00 sec)

mysql> INSERT into tab (c1,c2,c3,c4)     VALUES ('1','2','3','4')      ON DUPLICATE KEY UPDATE c3 = '4';
Query OK, 1 row affected (0.05 sec)

mysql> select * from tab;
+------+------+------+------+
| c1   | c2   | c3   | c4   |
+------+------+------+------+
|    1 |    2 |    4 |    4 |
|    1 |    2 |    3 |    4 |
+------+------+------+------+
2 rows in set (0.00 sec)

mysql> INSERT into tab (c1,c2,c3,c4)     VALUES ('1','2','3','4')      ON DUPLICATE KEY UPDATE c3 = '4';
ERROR 1062 (23000): Duplicate entry '4' for key 'c3_u'
mysql> select * from tab;
+------+------+------+------+
| c1   | c2   | c3   | c4   |
+------+------+------+------+
|    1 |    2 |    4 |    4 |
|    1 |    2 |    3 |    4 |
+------+------+------+------+
2 rows in set (0.00 sec)
于 2013-08-27T13:51:19.677 回答