书籍的数据库架构建议 - 文章 - 图片

时间:2015-09-18 10:46:33

标签: mysql sql database postgresql schema

我有以下型号。

Book has Articles (Article has foreign key to Book)

Article has Images (Article has upto #max number of foreign keys to images, Article have #max number of foreign key to images. which maybe null)

Furthermore I have Book - Image relation 
because certain images are included in the book but not owned by article

我让模型快速回答诸如

之类的查询
  • 给我一篇文章的图片。
  • 给我一本书的图像(按时间排序,如果需要,可以分页)

人们建议我的模型不好。 (when foreign key points to something else, move other data as well

想要了解更好的替代架构。

1 个答案:

答案 0 :(得分:0)

我会选择(假设postgresql数据库)的简单解决方案:

create table book (
  id integer primary key
);

create table article (
  id integer primary key,
  id_book integer references book(id)
);

create table image (
  id integer primary key,
  id_article integer references article(id),
  id_book integer references book(id),
  check ((id_article is null or id_book is null) and
    (id_article is not null or id_book is not null))
);

检查约束不允许将图像分配给文章或书籍。

  • 如果图片来自文章=> id_article已填写
  • 如果仅限于书籍(不是来自文章)=> id_book已填写
  

给我一​​本书的图像

select *
from book b
left join 
 (select *, id_book as book from image where id_article is null 
  union all
  select i.*, a.id_book as book from article a join image i on i.id_article=a.id) i on i.book = b.id;