[英]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.