MySQL:ALTER IGNORE TABLE 给出“完整性约束违规";

2021-11-20 00:00:00 mysql unique-constraint

我正在尝试使用 ALTER IGNORE TABLE + 一个唯一键从 MySQL 表中删除重复项.MySQL 文档说:

I'm trying to remove duplicates from a MySQL table using ALTER IGNORE TABLE + an UNIQUE KEY. The MySQL documentation says:

IGNORE 是标准 SQL 的 MySQL 扩展.如果新表中的唯一键存在重复项,或者在启用严格模式时出现警告,它会控制 ALTER TABLE 的工作方式.如果未指定 IGNORE,则复制将中止并在出现重复键错误时回滚.如果指定了 IGNORE,则只有第一行用于在唯一键上具有重复项的行.其他冲突行被删除.不正确的值被截断为最接近匹配的可接受值.

IGNORE is a MySQL extension to standard SQL. It controls how ALTER TABLE works if there are duplicates on unique keys in the new table or if warnings occur when strict mode is enabled. If IGNORE is not specified, the copy is aborted and rolled back if duplicate-key errors occur. If IGNORE is specified, only the first row is used of rows with duplicates on a unique key. The other conflicting rows are deleted. Incorrect values are truncated to the closest matching acceptable value.

当我运行查询时......

When I run the query ...

ALTER IGNORE TABLE table ADD UNIQUE INDEX dupidx (field)

...我仍然收到错误 #1062 - 键 'dupidx' 的重复条目 'blabla'.

... I still get the error #1062 - Duplicate entry 'blabla' for key 'dupidx'.

推荐答案

IGNORE 关键字扩展到 MySQL 似乎有一个 某些版本的 MySQL 上的 InnoDB 版本中的错误.

The IGNORE keyword extension to MySQL seems to have a bug in the InnoDB version on some version of MySQL.

您总是可以转换为 MyISAM,忽略添加索引,然后转换回 InnoDB

You could always, convert to MyISAM, IGNORE-ADD the index and then convert back to InnoDB

ALTER TABLE table ENGINE MyISAM;
ALTER IGNORE TABLE table ADD UNIQUE INDEX dupidx (field);
ALTER TABLE table ENGINE InnoDB;

请注意,如果您有外键约束,这将不起作用,您必须先删除它们,然后再重新添加.

Note, if you have Foreign Key constraints this will not work, you will have to remove those first, and add them back later.

相关文章