混淆是否以1:1使用HAS或BELONGS TO

时间:2018-06-09 23:10:59

标签: sql database-design

我知道将外键放在1:1的位置。

Owner(pet_id) [HAS] Pet
Pet(owner_id) [BELONGS TO] Owner

但请考虑一个例子:

Profile(section_id) [HAS] MoviesSection
Profile(section_id) [HAS] BooksSection

MoviesSection(profile_id) [BELONGS TO] Profile
BooksSection(profile_id) [BELONGS TO] Profile

如何决定是否要使用HAS或BELONGS TO例如如果我想“抓住个人资料的所有部分立即显示”。感觉这两种方法都有效吗?

HAS

profile
---
id movies_section_id books_section_id

movies_section
---
id favorite_movie favorite_actor

books_section
---
id favorite_book favorite_author

VS

属于

profile
---
id

movies_section
---
id profile_id favorite_movie favorite_actor

books_section
---
id profile_id favorite_book favorite_author

我应该问什么其他问题?例如,如果没有配置文件的情况下不能存在MoviesSection,那会有所不同吗?

1 个答案:

答案 0 :(得分:1)

也许不是你想要的答案,但我想用SQL术语来表达。您询问的部分:

Profile(section_id) [HAS] MoviesSection
Profile(section_id) [HAS] BooksSection

MoviesSection(profile_id) [BELONGS TO] Profile
BooksSection(profile_id) [BELONGS TO] Profile

会在SQL中看起来像:

create table profile (
  profile_id
);

create table moviessection (
  section_id,
  profile_id,
  constraint fk1 foreign key (section_id) references profile (profile_id)
);

create table bookssection (
  section_id,
  profile_id,
  constraint fk2 foreign key (section_id) references profile (profile_id)
);