簡體   English   中英

如何使用對父表的引用來規范表之間的關系

[英]How to normalize relationships between tables with references to a parent table

免責聲明我不太精通關系數據庫設計和規范化,但這是我遇到過的,我不確定這是否是規范化設計。 假設有一個父“公司”表

companies

ID 姓名
1 公司 1
2 公司 2

並且有在公司下創建的書籍和作者

books

ID company_id 姓名
1 1 小紅帽
2 2 雞皮疙瘩

authors

ID company_id 姓名
1 1
2 2 鮑勃

現在,如果我們想將書籍分配給作者,反之亦然:

books_authors

book_id author_id
1 1
2 2

但我們也將被允許連接不屬於同一公司的書籍和作者:

book_id author_id
1 2

還有比這更好的設計可以防止不同公司的書籍和作者相互關聯嗎? 我是否只需要添加一個檢查/約束來防止這種情況發生,還是有其他方法可以解決這個問題?

正如你所設置的,公司擁有這本書和作者。 這與現實不符; 作者寫書,公司出版書籍,一本書可以有許多公司出版的多個版本

正式地:

  • 一本書有很多作者。
  • 一本書有很多版本。
  • 一個版本有一個公司(出版商)。
  • 一本書通過他們的版本有許多公司。

從中我們可以得出...

  • 一個作者有很多書。
  • 一位作者的書有多個版本。
  • 一位作者通過他們的書的版本擁有許多公司。
  • 一家公司有很多版本。
  • 一家公司通過其版本擁有許多書籍。
  • 一家公司通過其版本的書籍擁有許多作者。
-- These can be publishers.
create table companies (
  id bigserial primary key,
  name text not null
);

-- These can be authors.
create table people (
  id bigserial primary key,
  name text not null
);

create table books (
  id bigserial primary key,
  title text not null
);

-- This can also include their role in the authoring.
-- For example: illustrator, editor
create table book_authors (
  book_id bigint not null references books,
  person_id bigint not null references people,

  -- Can't author the same book twice.
  unique(book_id, person_id)
);

-- This can also include information about the publishing such
-- as its year and language.
create table book_editions (
  book_id bigint not null references books,
  company_id bigint not null references companies,
  edition text not null,

  -- The same company can't publish the same edition twice.
  unique(book_id, company_id, edition)
);

這是一個通用的、靈活的書籍/作者/出版商模式。 但是,模式應該主要由您打算如何使用它來定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM