我们已经将MySQL(Percona)从5.6更新到5.7,并被告知某些表需要更改/修复,因为'datetime'字段现在有所不同。尽管在device_id和ts这两个字段上都有主键,但更改表失败并出现重复的输入错误,并且所有数据似乎都正常(没有重复)。据我所知,主键也必须是唯一的。
我们试图在WHERE部分中通过'device_id'和'ts'条件选择重复的条目,并且它仅找到该记录的1个实例。当我们尝试仅按ts字段选择时,它将找到同一记录的2个实例。那怎么可能?这些重复是什么?密钥是否损坏?除了创建新表并使用INSERT IGNORE传递所有数据以外,还有其他方法吗?
编辑:错误如下:
ERROR 1062 (23000): Duplicate entry '486-2014-10-26 02:39:33' for key 'PRIMARY'
编辑2:表结构如下(device_id,ts和32个传感器):
CREATE TABLE IF NOT EXISTS `sensor_log` (
`device_id` int(11) NOT NULL,
`ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`D1` smallint(6) DEFAULT NULL,
`D2` smallint(6) DEFAULT NULL,
...
`D30` smallint(6) DEFAULT NULL,
`D31` smallint(6) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
/*!50100 PARTITION BY RANGE ( UNIX_TIMESTAMP(ts))
(PARTITION p_sl_2013 VALUES LESS THAN (1388530800) ENGINE = InnoDB,
PARTITION p_sl_2014 VALUES LESS THAN (1420066800) ENGINE = InnoDB,
PARTITION p_sl_2015 VALUES LESS THAN (1451602800) ENGINE = InnoDB,
PARTITION p_sl_2016 VALUES LESS THAN (1483225200) ENGINE = InnoDB,
PARTITION p_sl_2017_q1 VALUES LESS THAN (1490997600) ENGINE = InnoDB,
PARTITION p_sl_2017_q2 VALUES LESS THAN (1498860000) ENGINE = InnoDB,
PARTITION p_sl_2017_q3 VALUES LESS THAN (1506808800) ENGINE = InnoDB,
PARTITION p_sl_2017_q4 VALUES LESS THAN (1514761200) ENGINE = InnoDB,
PARTITION p_sl_2018_q1 VALUES LESS THAN (1522533600) ENGINE = InnoDB,
PARTITION p_sl_2018_q2 VALUES LESS THAN (1530396000) ENGINE = InnoDB,
PARTITION p_sl_2018_q3 VALUES LESS THAN (1538344800) ENGINE = InnoDB,
PARTITION p_sl_2018_q4 VALUES LESS THAN (1546297200) ENGINE = InnoDB,
PARTITION p_sl_2019_q1 VALUES LESS THAN (1551394800) ENGINE = InnoDB,
PARTITION p_sl_2019_q2 VALUES LESS THAN (1556661600) ENGINE = InnoDB,
PARTITION p_sl_2019_q3 VALUES LESS THAN (1561932000) ENGINE = InnoDB,
PARTITION p_sl_2019_q4 VALUES LESS THAN (1567288800) ENGINE = InnoDB,
PARTITION p_sl_2019_q5 VALUES LESS THAN (1572562800) ENGINE = InnoDB,
PARTITION p_sl_2019_q6 VALUES LESS THAN (1577833200) ENGINE = InnoDB,
PARTITION p_sl_X VALUES LESS THAN MAXVALUE ENGINE = InnoDB) */;
--
-- Indexes for table `sensor_log`
--
ALTER TABLE `sensor_log`
ADD PRIMARY KEY (`device_id`,`ts`);
答案 0 :(得分:0)
当错误看起来像这样:
ERROR 1022 (23000): Can't write; duplicate key in table '#sql-6b04_a0'
然后,您可能要尝试两次创建具有相同名称的外键。或类似的东西。检查您的外键。
如果要将表更新强制为新格式,则无需对表进行任何更改。随便
ALTER TABLE foo FORCE;
编辑:
您的表中有重复的条目。您的主键跨越两列。用
查找那些重复项SELECT device_id, ts, COUNT(*)
FROM your_table
GROUP BY device_id, ts
HAVING COUNT(*) > 1
然后,您必须通过确保每个device_id和ts组合仅存在一个条目来清理表。