我试图通过创建索引在现有表上添加唯一性约束。
这是现有表(我试图使 mysql 的输出更具可读性):
mysql> show create table profile_status;
| Table | Create Table
| profile_status | CREATE TABLE `profile_status` (
`user_id` int(11) NOT NULL,
`timestamp` datetime DEFAULT NULL,
`proxy_profile_id` int(11) DEFAULT NULL,
KEY `user_id_refs_user_id` (`user_id`),
KEY `profile_status` (`proxy_profile_id`),
CONSTRAINT `proxy_profile_id_refs_user_id` FOREIGN KEY (`proxy_profile_id`) REFERENCES `profile_userprofile` (`user_id`),
CONSTRAINT `user_id_refs_user_id` FOREIGN KEY (`user_id`) REFERENCES `profile_userprofile` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
以下是我尝试创建索引时发生的情况:
mysql> CREATE UNIQUE INDEX `profile_status_unique` ON `profile_status` (`user_id`);
ERROR 156 (HY000): Table 'project.profile_status#1' already exists
我的第一个怀疑是错误消息具有误导性,事实上 MySQL 实际上拒绝在 user_id 列上创建第二个索引,因为那里已经有一个非唯一键。所以我尝试先删除该键(连同关联的外键约束):
mysql> ALTER TABLE profile_status DROP FOREIGN KEY user_id_refs_user_id;
Query OK, 112 rows affected (0.05 sec)
Records: 112 Duplicates: 0 Warnings: 0
mysql> ALTER TABLE profile_status DROP KEY user_id_refs_user_id;
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> show create table profile_status;
| Table | Create Table
| profile_status | CREATE TABLE `profile_status` (
`user_id` int(11) NOT NULL,
`timestamp` datetime DEFAULT NULL,
`proxy_profile_id` int(11) DEFAULT NULL,
KEY `profile_status` (`proxy_profile_id`),
CONSTRAINT `proxy_profile_id_refs_user_id` FOREIGN KEY (`proxy_profile_id`) REFERENCES `profile_userprofile` (`user_id`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
mysql> CREATE UNIQUE INDEX `profile_status_unique` ON `profile_status` (`user_id`);
ERROR 156 (HY000): Table 'project.profile_status#1' already exists
同样的结果。在这一点上,我完全被难住了,我真的很感激一些帮助。最坏的情况是,我可以创建一个具有正确约束的临时表并复制数据,但我想完全理解这个问题。
提前致谢。这是 MySQL 的详细信息:
mysql> show variables like '%version%';
| Variable_name | Value
| innodb_version | 1.1.8
| protocol_version | 10
| version | 5.5.28-1
| version_comment | (Debian)
| version_compile_machine | i686
| version_compile_os | debian-linux-gnu
7 rows in set (0.00 sec)
最佳答案
检查 MySQL 数据目录中的“项目”目录是否不包含任何不需要的/临时文件。如果您看到以类似 ? 开头的文件,请删除它们或者 #。还要检查名称为“profile_status#1”的文件是否存在并将其删除。
然后登录MySQL,执行FLUSH TABLES(即使在上面的步骤中没有不需要的文件)并再次尝试更改表。
关于mysql - 为什么 MySQL 在尝试创建索引时失败并显示 ERROR 156 "Table already exists"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18277283/