MySQL ERROR 1062(23000):重复输入' 2'关键'观看'?

时间:2017-10-03 15:50:54

标签: mysql

我有这个表定义:

mysql> DESCRIBE watched;
+---------+--------+------+-----+---------+----------------+
| Field   | Type   | Null | Key | Default | Extra          |
+---------+--------+------+-----+---------+----------------+
| id      | int(6) | NO   | PRI | NULL    | auto_increment |
| stream  | int(3) | NO   |     | 0       |                |
| month   | date   | NO   |     | NULL    |                |
| watched | int(6) | NO   | UNI | 1       |                |
+---------+--------+------+-----+---------+----------------+

这是里面的数据:

mysql> SELECT * FROM watched;
+----+--------+------------+---------+
| id | stream | month      | watched |
+----+--------+------------+---------+
|  1 |     11 | 2017-10-01 |       2 |
|  2 |     11 | 2017-10-01 |       1 |
+----+--------+------------+---------+
2 rows in set (0.00 sec)

当我运行此查询时:

INSERT INTO watched (stream, month) VALUES (11, DATE_FORMAT(NOW(), "%Y-%m-01")) ON DUPLICATE KEY UPDATE watched=watched+1;

我收到此错误:

ERROR 1062 (23000): Duplicate entry '2' for key 'watched'

id设置为PRIMARY并且AUTO_INCREMENT并且被监视设置为UNIQUE,以便我可以在sql语句中增加或减少监视值watched = watched + 1

但我不知道如何设置独特观察区域以增加或减少一个值...

编辑:

这是表结构:

mysql> SHOW CREATE TABLE watched;
+---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                                                                                                                                                                                                             |
+---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| watched | CREATE TABLE `watched` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `stream` int(3) NOT NULL DEFAULT '0',
  `month` date NOT NULL,
  `watched` int(6) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `watched` (`watched`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 |
+---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.03 sec)

1 个答案:

答案 0 :(得分:0)

我只需要根据Michael建议使用:

从watched.watched中删除UNIQUE
ALTER TABLE watched DROP INDEX watched

为流创建UNIQUE,就像找到增加计数器+ 1,如果没有插入新记录:

ALTER TABLE watched ADD UNIQUE (stream);

现在错误消失了,计数器增加了+ 1并且一切正常......上帝保佑MySQL:)