Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to model tables with foreign keys from several other tables

I'm attempting to create a contacts application that has two main entities - person and company. A person can have many emails, numbers, and addresses. A company can also have many emails, numbers, and addresses. I'm trying to determine the proper design for this scenario.

Option #1 - multiple foreign keys
Emails, numbers, and addresses will have two columns called person_id and company_id. Depending on which entity the data belongs to, one will be null and the other will contain an id linking back to the parent.

Option #2 - one table per type per entity
I duplicate each table so there would be a company_addresses table and a person_addresses table. I would have twice as many tables, but this is the solution that makes the most sense right now.

Option #3 - one link table
I create one table - "link". This table will contain four columns: source_id, source_entity, dest_id, dest_entity. So if a company gets a new number you would have a row like: 1, number, 2, company.

Option #4 - multiple link tables
I create a table for each type of link (company_address, person_address, company_email, person_email, etc.)

Which option would you choose?

like image 238
Amit Avatar asked Mar 16 '09 21:03

Amit


1 Answers

You've touched on a couple of practices I would argue that you avoid. I wrote more about this in Database Development Mistakes Made by AppDevelopers (eg exclusive arcs).

As to your problem, I would actually choose none of those options. What you're stumbling towards is a generic Party model. Basically you have a Party entity with subtypes such as Person and Organisation. Contacts has a Party ID as a foreign key. The use of a common superclass/superentity is much more profound than that however as you will find that you use this for many other things as well (eg the whole role concept).

A lot of these database design modelling problems have mature solutions to them but it doesn't tend to be the sort of thing programmers are ever taught. I highly recommend getting the book The Data Model Resource Book, Vol. 1: A Library of Universal Data Models for All Enterprises, which goes into much more detail about how to model people and organisations as well as many other typical problems.

The key point to remember here is that what you're doing has been done before.

like image 121
cletus Avatar answered Sep 24 '22 18:09

cletus