简体   繁体   English

无法在MySQL Workbench中创建外键

[英]Couldn't Create a Foreign Key in MySQL Workbench

I have two tables, let's call em table1 and table2 . 我有两个表,我们称它们为em table1table2

  • The Primary Key of table1 is CHAR(36), Not Null, and Unique. table1的主键是CHAR(36),Not Null和Unique。
  • The column in table2 I'm trying to make an FK is, also, CHAR(36), Not Null, and Unique. 我尝试制作FK的table2的列也是CHAR(36),Not Null和Unique。
  • Both tables have zero records. 两个表都有零个记录。
  • table1 has four Foreign Keys, all pointing at other tables. table1有四个外键,都指向其他表。 (None of them point at table2 .) (它们都没有指向table2

When I try to define the PK of table1 as an FK in table2 Workbench wouldn't let me select the field. 当我尝试将table1的PK定义为table2的FK时,Workbench不允许我选择该字段。 The check box for the column in table2 simply would not be selected, no matter what I did. 无论我做什么,都不会选择table2中该列的复选框。

In order to create this Foreign Key, I had to run it as a query directly, bypassing Workbench's GUI. 为了创建此外键,我不得不绕过Workbench的GUI直接将其作为查询运行。

ALTER TABLE `my_schema`.`table_two` 
ADD INDEX `fk_to_table_one_pk_idx` (`table_two_column` ASC);
ALTER TABLE `my_schema`.`table_two` 
ADD CONSTRAINT `fk_to_table_one_pk`
    FOREIGN KEY (`table_two_column`)
    REFERENCES `my_schema`.`table_one` (`table_one_column`)
    ON DELETE RESTRICT
    ON UPDATE CASCADE;

I ran this query and, ta-friggin-da, the FK was in place and no error was thrown. 我运行了此查询,并且ta-friggin-da设置了FK,并且未引发任何错误。 I've heard that Workbench is pretty flaky and I think this confirms that. 我听说Workbench非常脆弱,我认为这证实了这一点。

After I had the FK in place I marked the column in table2 as the PK via the GUI without issue. 放置好FK之后,我通过GUI将table2的列标记为PK,没有问题。 The SQL might have worked just fine with the table2 column marked as the PK but I did not run it that way, so I cannot confirm that. 在标记为PK的table2列上,SQL可能工作得很好,但是我没有那样运行,因此无法确认。

Try DISABLE KEYS or 尝试禁用键或

SET FOREIGN_KEY_CHECKS=0;

make sure to 确保

SET FOREIGN_KEY_CHECKS=1;

after. 后。

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

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