InnoDB 关系:单向还是双向?

发布于 2024-11-30 22:14:17 字数 340 浏览 0 评论 0原文

我第一次决定切换到 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 技术交流群。

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

发布评论

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

评论(1

盗心人 2024-12-07 22:14:17
  • 1 用户有许多小部件

假设一个小部件是一个用户独有的(因为您有一个多对多的单独点):表 widget 上的 user_id 引用了主键user

  • 小部件属于 1 个用户,

请参见上面的内容。

  • 1 个用户在 user 表中拥有 1 个小部件

widget_id,该小部件引用 widget 表上的主键,并在 widget_id 上具有唯一索引,或者反过来,并不重要。如果是 1 对 1 而不是 0 或 1 对 1 关系,则应考虑将 widget 和用户放在一张表中。

  • user [many-to-many] widgets

引入第三个表 user_widget,其中有 2 个字段 user_idwidget_id 引用 user 中相应的主键和小部件表。

  • 许多用户共享 1 个小部件,

与“1 个用户有 1 个小部件”相同,但 widget_id 上没有唯一索引

ON CASCADE 选项从父级(主键)到子级起作用(外键/参考)。因此,如果您在第一个场景中有一个ON DELETE CASCADE(1 个用户有许多小部件),则删除用户会删除他的所有小部件,但删除所有小部件不会删除该用户。

  • 1 User has many widgets

Assuming a widget is exclusive to one user (because you have a seperate point for many to many): user_id on table widget that references the primary key on user

  • widget belongs to 1 user

see above.

  • 1 user has 1 widget

widget_id in user table that references primary key on widget table, with unique index on widget_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.

  • user [many-to-many] widgets

Introduce a third table, user_widget, with 2 fields user_id and widget_id referencing the corresponding primary keys in user and widget table.

  • many users share 1 widget

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 a ON 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.

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