简体   繁体   English

无法在mysql表中创建约束

[英]unable to create constraint in mysql table

I've got following tables: 我有以下表格:

node_sharing | CREATE TABLE `node_sharing` (
  `user_id` int(11) NOT NULL,
  `node_id` int(11) NOT NULL,
  PRIMARY KEY (`user_id`,`node_id`),
  KEY `fk_user_id_idx` (`user_id`),
  KEY `fk_node_id_idx` (`node_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

and

users | CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `has_ard_access` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

I would like to create following foreign key with a constraint: 我想用约束创建以下外键:

ALTER TABLE `node_sharing`
  ADD CONSTRAINT `fk_user_id`
  FOREIGN KEY (`user_id` )
  REFERENCES `users` (`id` )
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;

and MySQL returns the following error: 和MySQL返回以下错误:

ERROR 1005 (HY000): Can't create table 'MY_TABLE_NAME.#sql-4d0_218' (errno: 121)

What is wrong here? 这有什么不对?

PS node_sharing has been truncated, so there are no existing records that could disable putting the constraint on. PS node_sharing已被截断,因此没有现有记录可以禁用放置约束。

It is a duplicate key error. 这是一个重复的键错误。 Did you have a table with same name before? 你之前有一张同名的桌子吗? If so, check InnoDB internal data dictionary. 如果是这样,请检查InnoDB内部数据字典。 If not, check if you have another constraint with same name. 如果没有,请检查是否有另一个具有相同名称的约束。 Constraint names should be unique. 约束名称应该是唯一的。

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

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