Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

sql server - Best way to design this database scenario?

Requirement is to store attachments for different entity types.

Say we have 3 entity types Company , Department and Employee. Each can have multiple attachments (documents).

Which is the best way to handle this?

Solution 1:

Company table

  • CompanyId

Dept table

  • DeptId

Employee table

  • EmployeeId

AttchmentType table

  • TypeId
  • Types (company, dept, employee)

Attachments table

  • AttachmentId
  • TypeId (maps to attachment type)
  • entityId (maps to CompanyId / DeptId / EmployeeId)

Pros: I can add new entity types easily in future

Cons: In this case I can't have foreign key relationship maintained between entities and attachments.

Solution 2:

Company table

  • CompanyId

Dept table

  • DeptId

Employee table

  • EmployeeId

CompanyAttachments table

  • AttachmentId
  • CompanyId (FK)

DeptAttachments table

  • AttachmentId
  • DeptId (FK)

EmployeeAttachments table

  • AttachmentId
  • EmployeeId (FK)

Pros: Foreign key integrity

Cons: In order add new entity I need to have new attachment table separately.

So which is the best way to go with assuming I may need to add new entities in future?


Edit 1:

Thanks for your reply guys.

If I want to go with solution 2, I see that creating new columns in attachments table easier instead of creating new attachment tables for every entity just to map them? something like,

Company table

  • CompanyId

Dept table

  • DeptId

Employee table

  • EmployeeId

Attachments

  • AttachmentId
  • CompanyId (FK)
  • EmployeeId (FK)
  • DepartmentId (FK)

am I missing something here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'd definitely go with solution #2. Your one pro for solution #1 isn't really a pro. If you add a new entity you're going to necessarily have to already add a new table for that entity and you'll already be adding or changing existing code to handle it. You should be able to make some generic objects that handle the pattern so that duplicated code isn't a problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...