I have a website I develop that is structured a little like stackoverflow. I have a Posts table and a PostImages table in the database. The PostImages table looks like this:
PostImageId PK
PostId FK
Uri
MimeType
So posts can have lots of images associated with them.
I now have the requirement that other places on the site should have images: Users should be able to have images on their profile, Categories should be able to have images, and Addresses should be able to have images.
It seems best to only have a single Images table in my database. How should I model this? I could have a single table like this:
ImageId PK
PostId FK
CategoryId FK
AddressId FK
UserId FK
Uri
MimeType
I could have a single images table, then extra tables for each kind of object:
PostImageId PK FK
PostId FK
CategoryImageId PK FK
CategoryId FK
(where the PK of each item is also FK to an image from the Images table)
There are some other strategies, too: for instance, I could have a ___Images table for each type, and no shared Images table. I could have a many-to-many mapping table for each, and perhaps there are some other solutions I haven’t thought of.
What is best? I don’t know that much about database design – which will be the most flexible and easiest to use?
In real life projects, Database is designed regarding to the cost of accessibility of data. You mentioned two ways of designing your tables. Both are correct. If you put all your fields in one table there will be data redundancy. If you make two tables there is no problem.
But you have to keep in mind that joining two tables will cost more. So while fetching data from your server, this may make your page slow (If concurrently a lot of users try at the same time).
On the other hand, if you put it in one field, it will take more memory in database but less cost in data fetching. The choice is yours.