简体   繁体   中英

Multiple one to many relationship design

At the moment, we have this design for storing objects with multiple image/video URLs:

tblCompany:
pkCompanyId

tblPerson:
pkPersonId

tblImage:
pkImageId
ImageUrl
fkCompanyId
fkPersonId

While this design handles:

  1. A company having multiple images
  2. A person having multiple images

I can't help feeling that there is a problem with this design as rows in tblImage will have tons of NULL values for the foreign key columns.

Is there a better design? More objects (some unrelated to company or person, some related to company or person) in the design will have images so with the current design tblImage could have more and more foreign keys.

This is actually a pretty good design for just 2 entities that can have images. Yes, you'll have plenty of NULLs, but alternatives (such as separate image tables, or specially crafted 1:N link tables) will have their problems too.

Since this is a 1:N relationship, we don't need any additional M:N junction/link tables.


In case you need to add more kinds of entities that can have images, you could consider inheritance, like this:

在此输入图像描述

This way, an image will automatically be able to connect to any entity that inherits from the tblCommon , no matter how many kinds of entities there are. Unfortunately, inheritance is not directly supported in relational DBMSes, so you'll have to emulate it in one of 3 ways , each with its own set of compromises.

If I understand the schema correctly, Company and Person are unrelated and both can have one or more images. Then you could just have a table for images themselves and two different tables for company to image and person to image mappings.

tblCompany: pkCompanyId
tblPerson: pkPersonId    
tblImage: pkImageId ImageUrl    
tblPersonImage: fkImageId fkPersonId    
tblCompanyImage: fkImageId fkCompanyId

This schema also enables you to associate an image to other kind of entities too in future (like a Product).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM