sql 中的“REFERENCES”有什么作用?
我正在尝试用简单的示例编写一个多模式。我有一张表books
映射到许多标签
。 (请参阅下面的小提琴链接)
我想要的是标签表具有书籍表的外键。我想我已经做到了这一点:
CREATE TABLE IF NOT EXISTS `books` (
`id` int(6) unsigned NOT NULL,
`book_name` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `tags` (
`tag_id` int(6) unsigned NOT NULL,
`tag` varchar(100) NOT NULL,
`book_id` int(6) unsigned NOT NULL,
PRIMARY KEY (`tag_id`)
);
我不明白之间的区别:
`book_id` int(6) unsigned NOT NULL,
和
`book_id` int(6) unsigned NOT NULL REFERENCES `books`(`id`),
两者都可以正常编译并使用内部联接
http://sqlfiddle.com/#!9/612337/1
http://sqlfiddle.com/#!9/2043b8/3
那么这些片段之间有什么区别呢?
I'm trying to write a 1-many schema with simple example. I have one table books
mapping to many tags
. (see fiddle links below)
What I want is for the tags table to have a foreign key to books table. I think I have managed this:
CREATE TABLE IF NOT EXISTS `books` (
`id` int(6) unsigned NOT NULL,
`book_name` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `tags` (
`tag_id` int(6) unsigned NOT NULL,
`tag` varchar(100) NOT NULL,
`book_id` int(6) unsigned NOT NULL,
PRIMARY KEY (`tag_id`)
);
I don't understand the difference between:
`book_id` int(6) unsigned NOT NULL,
and
`book_id` int(6) unsigned NOT NULL REFERENCES `books`(`id`),
Both compile fine and work with inner joins
http://sqlfiddle.com/#!9/612337/1
http://sqlfiddle.com/#!9/2043b8/3
So what's the difference between the snippets?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
https://dev.mysql.com/ doc/refman/8.0/en/ansi-diff-foreign-keys.html 说:
也就是说,以下命令创建列
book_id
但不是外键约束:您必须这样做方式:
几年前就决定跳过将内联引用作为列选项的实现。如果您为两列或更多列创建了外键,则无论如何您都必须对 FOREIGN KEY 约束使用单独的行。作为列定义一部分的内联 REFERENCES 只是一种方便的快捷语法。
至少从 2004 年起,语法被解析但被忽略的事实就被报告为错误,但从未修复:
但由于MySQL可插拔存储引擎架构,修复这个bug比较困难。 SQL 语法解析是独立于存储引擎处理的,但约束的实现是在存储引擎内处理的。 SQL 解析器必须允许该语法,因为它不知道给定存储引擎是否会忽略或支持该功能。
https://dev.mysql.com/doc/refman/8.0/en/ansi-diff-foreign-keys.html says:
That is, the following creates the column
book_id
but not a foreign key constraint:You must do it this way:
The decision was made years ago to skip implementing inline REFERENCES as a column option. You would have to use the separate line for the FOREIGN KEY constraint anyway if you made a foreign key for two or more columns. The inline REFERENCES as part of a column definition is just a convenient short-cut syntax.
The fact that the syntax is parsed but ignored has been reported as a bug since at least 2004, but never fixed:
But because of MySQL pluggable storage engine architecture, it's difficult to fix this bug. SQL syntax parsing is handled independently of the storage engine, but implementation of constraints is handled within the storage engine. The SQL parser must allow the syntax, because it doesn't know whether the feature will be ignored or supported by a given storage engine.