为什么在MySQL中的列级定义时未创建外键?

发布于 2025-01-31 13:21:29 字数 436 浏览 3 评论 0原文

我使用以下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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

木落 2025-02-07 13:21:29

这是MySQL中的功能请求可以追溯到2004年,但从未实施过。 https://bugs.mysql.com/bug.com/bug.php?id=4919

解决方法是使用表级外键约束语法,即使您的情况允许列级约束,因为它仅适用于单个列。

create table Score ( 
 rollno int, 
 marks int,
 foreign key(rollno) references student(rollno) 
);

这种缺失功能的原因可能不满意,但是这里是从Innodb的建筑师那里:

mySQL不会给出语法错误,因为这是1990年代的意图,该表定义包含外键约束的定义也应导入mySQL,即使当时的MySQL不支持外国键。

对于根本不支持外国钥匙的其他存储引擎(例如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.

create table Score ( 
 rollno int, 
 marks int,
 foreign key(rollno) references student(rollno) 
);

The reason for this missing feature may be unsatisfying, but here it is, from the architect of InnoDB:

MySQL does not give a syntax error, because it was the intention in the 1990's that table definitions containing FOREIGN KEY constraints should be importable to MySQL, even though MySQL at that time did not support foreign keys.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文