I will explain my case with an example.
I have the following tables: persons, places, pictures. Both persons and places have many pictures. What is the best way to express this in a database scheme while maintaining referential integrity?
- I could add a column for each possible association, but this will create a lot of empty fields when there are other things that have pictures, too.
- I could create association tables between
personsandpicturesandplacesandpictures. But then the foreign keys would be in the association table and I cannot enforce that pictuers are deleted when places etc. are deleted.
At the moment I lean towards the second approach, but I do not like it.
There’s no one-size fits all solution that will tick all of the boxes you want. But one I’ve seen before is
3) Introduce a base table for items that will share relationships:
And then build your
PeopleandPlacestables:(I’m not sure
Entitiesis exactly right when thinking about places – a better name may suggest itself to you).You can then have
Picturesjust references theEntityID.Otherwise, if I had to pick between 1 & 2, I’d usually recommend 1. Unless the number of “types” involved gets large, it still doesn’t make the
Picturestable too wide, and as you’ve observed, you can at least use the normal FK mechanisms to enforce cascades, if necessary.4) If
Picturesis just a very bare table at the moment, maybe query whether there ought to be one pictures table, or one per type. Will pictures of people and pictures of places frequently end up queried together (and even if they are, could aUNION ALLbased query hide the fact that you’re using separate tables)?