我有以下型号。
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)
想要了解更好的替代架构。
答案 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;