【问题标题】:database schema suggestion for book - article - image书籍 - 文章 - 图像的数据库架构建议
【发布时间】:2015-12-15 11:44:37
【问题描述】:

我有以下型号。

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)

想知道更好的替代架构。

【问题讨论】:

  • 这是“模式”。此外,您应该拥有最大数量的任何东西。您还需要一个文章-图像关系表。
  • @JonathonReinhart:我稍微编辑了 OP。文章有 #max 个外键字段(其中一些可能为空)到 Image。有文章图像表更好吗?为什么?
  • MySQL 和 Postgresql 的模式定义相同?一个棘手的...
  • @jarlh:不应该包含 mysql 或 postgresql 作为标签? :(
  • 因为这是一个数据建模问题,所以数据库引擎并不重要。如果这是我的数据库,我会在文章中添加一条默认记录,其名称类似于“不是文章”。然后,您可以将没有真实文章的图像分配给该记录,并摆脱您的书籍图像关系。此外,如果一篇文章可能出现在不止一本书中,那么您就有问题了。

标签: mysql sql database postgresql schema


【解决方案1】:

我会选择简单的解决方案(假设是 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;

【讨论】:

  • 怎么样,sorted bytime, paginated?
  • @eugene,只需将order by time limit <limit> offset <offset> 添加到我的查询中即可。还不够吗?
猜你喜欢
  • 2012-02-28
  • 2012-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-24
  • 2015-06-18
  • 1970-01-01
相关资源
最近更新 更多