InnoDB 关系:单向还是双向?
我第一次决定切换到 InnoDB 并尝试外键和其他 InnoDB 功能。
创建关系时,我应该只在一张表上声明它们吗?还是两张桌子都可以?
例如,对于下面的每种情况,您将在哪里以及如何声明关系?
- 1 个用户有很多小部件 小
- 部件属于 1 个用户(与上面相同吗?)
- 1 个用户有 1 个小部件
- 用户 [多对多] 小部件
- 许多用户共享 1 个小部件
这些只是一些随机示例,我只是想了解应该声明哪些方向的关系。
另外,同样,“ON CASCADE”的东西朝哪个方向工作?
谢谢
I've decided for the first time to switch to InnoDB and experiment with foreign keys and other InnoDB features.
When creating relationships, should I declare them only on 1 table? Or both tables?
For example, for each cases below, where and how would you declare the relationships?
- 1 User has many widgets
- widget belongs to 1 user (is that same as above?)
- 1 user has 1 widget
- user [many-to-many] widgets
- many users share 1 widget
Those are just some random examples, I'm just trying to understand which directions relationships should be declared.
Also, on the same note, which direction do "ON CASCADE" stuff work?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设一个小部件是一个用户独有的(因为您有一个多对多的单独点):表
widget
上的user_id
引用了主键user
请参见上面的内容。
user
表中拥有 1 个小部件widget_id
,该小部件引用widget
表上的主键,并在widget_id
上具有唯一索引,或者反过来,并不重要。如果是 1 对 1 而不是 0 或 1 对 1 关系,则应考虑将 widget 和用户放在一张表中。引入第三个表
user_widget
,其中有 2 个字段user_id
和widget_id
引用 user 中相应的主键和小部件表。与“1 个用户有 1 个小部件”相同,但
widget_id
上没有唯一索引ON CASCADE
选项从父级(主键)到子级起作用(外键/参考)。因此,如果您在第一个场景中有一个ON DELETE CASCADE
(1 个用户有许多小部件),则删除用户会删除他的所有小部件,但删除所有小部件不会删除该用户。Assuming a widget is exclusive to one user (because you have a seperate point for many to many):
user_id
on tablewidget
that references the primary key onuser
see above.
widget_id
inuser
table that references primary key onwidget
table, with unique index onwidget_id
, or the other way around, doesn't really matter. If it is a 1-to-1 and not a 0 or 1-to-1 relationship, you should consider putting widget and user in one table.Introduce a third table,
user_widget
, with 2 fieldsuser_id
andwidget_id
referencing the corresponding primary keys in user and widget table.same as "1 user has 1 widget", but without a unique index on the
widget_id
The
ON CASCADE
option works from parent (primary key) to child (foreign key/reference). So if you have aON DELETE CASCADE
in your first scenario (1 User has many widgets), delete a user deletes all his widgets, but deleting all widgets doesn't delete the user.