开发者

InnoDB relationships: one-way or two-way?

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 h开发者_StackOverflow中文版ow 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


  • 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜