如何在 MySQL 中真正创建外键?
这听起来像是一个愚蠢的问题,因为实际上有数百个教程。
但无论我按照哪个教程创建外键
,或者在我的例子中,创建复合外键
,即使表创建总是成功,MySQL Workbench 也不会显示任何外键
信息。
如果我创建这两个示例表
CREATE TABLE parent (
id INT NOT NULL,
category VARCHAR(255) NOT NULL,
PRIMARY KEY (id, category)
);
CREATE TABLE child (
id INT PRIMARY KEY,
category VARCHAR(255) NOT NULL,
info TEXT,
CONSTRAINT fk FOREIGN KEY (id, category) REFERENCES parent(id, category)
);
我缺少什么?这确实是很奇怪的行为,它们既不是 MySQL Workbench 显示的错误也不是警告。
This sounds like a stupid question, because there's literally hundreds of tutorials out there.
But no matter which tutorial I follow to create a foreign key
or, in my case, a composite foreign key
, even though the table creation is always successful, MySQL Workbench does not show any foreign key
information.
If I create these 2 example tables
CREATE TABLE parent (
id INT NOT NULL,
category VARCHAR(255) NOT NULL,
PRIMARY KEY (id, category)
);
CREATE TABLE child (
id INT PRIMARY KEY,
category VARCHAR(255) NOT NULL,
info TEXT,
CONSTRAINT fk FOREIGN KEY (id, category) REFERENCES parent(id, category)
);
The table creation is successful but the foreign key is not listed.
What am I missing? This is really weird behavior that their is neither an error nor a warning shown by MySQL Workbench.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在 MySQL Workbench 8.0.28 中测试了您的示例表。它使用其外键成功创建了
子
表。我运行了 SHOW CREATE TABLE child ,输出显示了外键。但是 MySQL Workbench 显然有一个在可视表信息中显示外键的错误。我像你一样查看了外键选项卡。我按下“刷新”按钮并收到以下消息:
我检查了日志(帮助->显示日志文件)并看到了以下内容:
此错误于 2021 年 2 月报告:https://bugs.mysql.com/bug.php?id=102496(以及上面评论中的重复错误 ysth 链接)。该错误是“已验证”,这意味着 MySQL 团队承认它是一个错误,但没有修复,也没有估计何时修复。
I tested your example tables in MySQL Workbench 8.0.28. It successfully created the
child
table with its foreign key. I ranSHOW CREATE TABLE child
and the output shows the foreign key.But MySQL Workbench apparently has a bug showing the foreign key in the visual table information. I viewed the foreign keys tab as you did. I pressed the "refresh" button and got this message:
I checked the log (Help->Show Log File) and saw this:
This bug was reported in February 2021: https://bugs.mysql.com/bug.php?id=102496 (and also the duplicate bug ysth links to in the comments above). The bug is "Verified" which means the MySQL team acknowledges it as a bug, but there is no fix and no estimate for when there will be a fix.