I am quickly learning the ins and outs of database design (something that, as of a week ago, was new to me), but I am running across some questions that don’t seem immediately obvious, so I was hoping to get some clarification.
The question I have right is about foreign keys. As part of my design, I have a Company table. Originally, I had included address information directly within the table, but, as I was hoping to achieve 3NF, I broke out the address information into its own table, Address. In order to maintain data integrity, I created a row in Company called “addressId” as an INT and the Address table has a corresponding addressId as its primary key.
What I’m a little bit confused about (or what I want to make sure I’m doing correctly) is determining which table should be the master (referenced) table and which should be the child (referencing) table. When I originally set this up, I made the Address table the master and the Company the child. However, I now believe this is wrong due to the fact that there should be only one address per Company and, if a Company row is deleted, I would want the corresponding Address to be removed as well (CASCADE deletion).
I may be approaching this completely wrong, so I would appreciate any good rules of thumb on how to best think about the relationship between tables when using foreign keys. Thanks!
Think of it as a has or has many relationship.
A company definitely has an address (in your example) so it should be the parent table and the address table should reference the company table. If, on the other hand, many different companies shared the same address, it could be the other way round. So it also depends on your needs (the logic you are trying to model).