为什么在MySQL中的列级定义时未创建外键?
我使用以下SQL命令创建了一个名为“学生”的父表,其中有两个列为“ Rollno”和“名称”:
create table Student
(
rollno int primary key,
name char(30)
);
我在列级上定义了主要约束,并且创建了主键。但是,当我使用以下sql命令创建了两个列为“ rollno”和“标记”的子表“得分”时,
create table Score
(
rollno int references student(rollno),
marks int
);
未创建外键(当在列级定义时)。我也没有任何错误。如果我在表级别上应用外键约束,则将创建外键。
因此,我的疑问是为什么在列定义在列级时创建主键时在列级定义时未创建外键?
我正在使用MySQL的最新版本。
I created a parent Table named 'Student' having two columns as 'rollno' and 'name' using the following SQL command:
create table Student
(
rollno int primary key,
name char(30)
);
I defined primary constraint at the column level and the primary key got created. However, when I created child table 'Score' containing two columns as 'rollno' and 'marks' using the following SQL command:
create table Score
(
rollno int references student(rollno),
marks int
);
Foreign key was not created (when defined at the column level). I didn't get any error too. If I apply foreign key constraint at the table level then the foreign key gets created.
So, my doubt is why foreign key is not created when defined at the column level while the primary key is created when defined at the column level?
I am using latest version of MySQL.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是MySQL中的功能请求可以追溯到2004年,但从未实施过。 https://bugs.mysql.com/bug.com/bug.php?id=4919
解决方法是使用表级外键约束语法,即使您的情况允许列级约束,因为它仅适用于单个列。
这种缺失功能的原因可能不满意,但是这里是从Innodb的建筑师那里:
对于根本不支持外国钥匙的其他存储引擎(例如Myisam),也可以接受外键语法但被忽略。没有返回错误或警告,但未保存外键约束。
This is a feature request in MySQL that dates back to 2004, but it has never been implemented. https://bugs.mysql.com/bug.php?id=4919
The workaround is to use table-level foreign key constraint syntax, even if your case would allow a column-level constraint because it's only for a single column.
The reason for this missing feature may be unsatisfying, but here it is, from the architect of InnoDB:
For other storage engines that don't support foreign keys at all (e.g. MyISAM), it is also the case that the foreign key syntax is accepted but ignored. No error or warning is returned, but the foreign key constraint is not saved.