将外键添加到现有表中会出现错误1050表

ava*_*ske 20 mysql foreign-keys mysql-workbench mysql-error-1050

我有一个包含列的表CustomizationSet:

customization_set_guid (which is a non-nullable guid and also the primary key)
creator_account_guid
and a few others
Run Code Online (Sandbox Code Playgroud)

和包含现有数据的表注册列:

registration_id (an int and the primary key)
customization_set_guid (also a guid (so a char(36)) which is nullable, and all entries are currently null)
and a few other columns
Run Code Online (Sandbox Code Playgroud)

当我试着跑

ALTER TABLE Registration ADD FOREIGN KEY 
    (
        customization_set_guid
    ) REFERENCES CustomizationSet (
        customization_set_guid
    );
Run Code Online (Sandbox Code Playgroud)

在MySQL Workbench中,它给出了错误1050Table'.\ dbname\registration'已经存在.

如果我尝试使用UI使用Alter Table对话框的Foreign Keys选项卡添加外键,并选择CustomizationSet作为引用表,则不允许我在列列表中选择customization_set_guid.

我真的不确定为什么它不会让我添加这个外键.我刚刚在我刚刚添加的表之间成功创建了外键.注册表已经存在了一段时间......

小智 9

我得到了同样的错误,这是因为外键已经存在.你想要的只是添加约束:

ALTER TABLE Registration 
  ADD CONSTRAINT idx_Registration_CustomizationSet 
  FOREIGN KEY (customization_set_guid) 
  REFERENCES CustomizationSet(customization_set_guid);
Run Code Online (Sandbox Code Playgroud)

  • 你不必.我的问题是我做了,在做了一些阅读后,我意识到我正在尝试添加一个已经存在的约束.删除约束使MySQL自己分配名称.这来自http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html:"如果给出了CONSTRAINT符号子句,则符号值在数据库中必须是唯一的.如果没有给出该条款,InnoDB会自动创建名称." (2认同)
  • 这实际上对我有用。显式地为约束命名有效。奇怪,因为这个表没有现有的约束。 (2认同)
  • 如果有人能向我解释为什么这项工作有效,我会很高兴听到。它解决了问题,但我不知道为什么 (2认同)

ava*_*ske 2

所以一个团队成员想出了这个办法。其中一个表设置为 utf8_general 类型,另一个表设置为默认类型。我不认为这是一个问题,因为默认值是 utf8_general,但显然 mysql 只查看类型名称而不是底层类型。