繁体   English   中英

MySQL:无法创建表

[英]MySQL: Can't create table

我尝试使用下面的CREATE TABLE语句在MySQL中创建一个表:

CREATE TABLE `visit` (
  `visit_id` int(11) NOT NULL,
  `site_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`visit_id`),
  CONSTRAINT `FK_visit_site` FOREIGN KEY (`site_id`) REFERENCES `site` (`site_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我收到了这个错误:

ERROR 1005(HY000):无法创建表'fooschema.visit'(错误号:121)

我使用了SHOW ENGINE INNODB STATUS命令。 这是错误消息:

------------------------
LATEST FOREIGN KEY ERROR
------------------------
140222  7:03:17 Error in foreign key constraint creation for table `fooschema`.`visit`.
A foreign key constraint of name `fooschema/FK_visit_site`
already exists. (Note that internally InnoDB adds 'databasename/'
in front of the user-defined constraint name).
Note that InnoDB's FOREIGN KEY system tables store
constraint names as case-insensitive, with the
MySQL standard latin1_swedish_ci collation. If you
create tables or databases whose names differ only in
the character case, then collisions in constraint
names can occur. Workaround: name your constraints
explicitly with unique names.

然后,我使用下面的查询列出所有可用的约束:

select *
from information_schema.table_constraints
where constraint_schema = 'fooschema'

我没有在结果中看到名称为“FK_visit_site”的任何约束。

FK_visit_site约束是表访问的外键约束。 我删除了访问表并尝试重新创建它。

有没有办法我可以删除这个外键约束,即使它所关联的表不存在?

您的外键已经存在,因此要么删除已存在的外键,要么重命名您的第二个键。

 ALTER TABLE `site` DROP FOREIGN KEY `FK_visit_site`;

或重命名为其他新的。

CREATE TABLE `visit` (
 `visit_id` int(11) NOT NULL PRIMARY KEY,
 `site_id` int(11) NOT NULL,
CONSTRAINT `FK_visit_site` FOREIGN KEY (`site_id`) REFERENCES `site` (`site_id`),
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

visit_id行添加了PRIMARY KEY

注意:

确保site_idsite表具有精确相同的数据类型site_id在访问表。

像那样

  `site_id` int(11) DEFAULT NULL  --//in the `site` table 

您正在耦合的两个键必须具有完全相同的数据类型(INT NOT NULL),甚至是signedness

AFAIK,当您尝试添加具有已在其他位置使用过的名称的约束时,您将收到此错误。 意味着,在你的情况下,FK FK_visit_site之前已经被使用过了。

如果您尝试创建的表包含外键约束,并且您已为该约束提供了自己的名称,请记住它在数据库中必须是唯一的。

您可以运行以下查询以查找相同的内容

SELECT
  constraint_name,
  table_name
FROM
  information_schema.table_constraints
WHERE
  constraint_type = 'FOREIGN KEY'
  AND table_schema = DATABASE()
ORDER BY
  constraint_name;

取自这里的帖子http://www.thenoyes.com/littlenoise/?p=81

尝试为您的FK使用不同的名称

CREATE TABLE `visit` (
  `visit_id` int(11) NOT NULL,
  `site_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`visit_id`),
  CONSTRAINT `FK_visit_site_New` FOREIGN KEY (`site_id`) 
  REFERENCES `site` (`site_id`),
) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM