mySQL中外键必须是索引吗?
我刚刚自己创建了第一个 mySQL 表(除了使用 Joomla、Wordpress 等),我是 MS SQL 开发人员多年,但通常我可以轻松地在 MS SQL 中创建外键,但我遇到了困难或这里缺乏知识。
这是我的表格:
users
- user_id int Primary auto_increment
- username varchar(20)
- password varchar(20)
posts
- post_id in Primary auto_increment
- title varchar(100)
- message text
- user_id int
当我尝试向引用 posts->user_id
的用户添加外键,我在 mySQL 面板上的选项列表 Relation_view 窗口中看不到 posts->user_id
选项。
我想知道是否应该将 posts->user_id
定义为 Index
或者其他什么?如果是这样,为什么?
I've just created my first mySQL table on my own (other than using Joomla, Wordpress, etc.) and I am MS SQL developer for years but normally I can easily create a foreign key in MS SQL but I came across a difficulty or lack of knowledge here.
Here is my tables :
users
- user_id int primary auto_increment
- username varchar(20)
- password varchar(20)
posts
- post_id in primary auto_increment
- title varchar(100)
- message text
- user_id int
When I try to add a foreign key to users which refers to posts->user_id
, I cannot see the posts->user_id
option in the option list Relation_view window on mySQL panel.
I am wondering whether I should define posts->user_id
as Index
or something? If so, why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简短的回答:是的,MySQL 强制你索引外键。
您可以在 MySQL 文档页面上阅读有关外键的更多信息: http:// dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
Short answer: Yes, MySQL forces you to index foreign key.
You can read more about foreign keys on MySQL documentation pages: http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
来自 MySQL 参考手册:
与 SQL Server 不同,SQL Server 不需要对 FK 建立索引...但是,我看到的建议表明您几乎总是对 FK 建立索引,即使这不是必需的。
From the MySQL Reference Manual:
In contrast to SQL Server, which does not require FKs to be indexed... however the recommendations that I've seen suggest that you almost always being indexing your FKs even though it isn't required.
来自文档:
From the documentation: