Database Design – Best Way to Handle Different Attachment Types

database-designnormalizationtable

I am currently Building a table for message where user can send a message with different types of attachment,

Sender can:

  • send text per message
  • send one location per message
  • send one or multiple images per message
  • send one or multiple videos per message

Currently, this is my table design,

message 
    -id
    -type (text,images,videos,location)
    -sender_id

message_text
    -id
    -message_id
    -body

message_location
    -id
    -message_id
    -latitude
    -longitude

message_images
    -id
    -message_id
    -image_path
    -image_height
    -image_width

message_videos
    -id
    -message_id
    -video_path

Am I doing things right?

My concern was user can attach multiple of images or videos but only one location.

Best Answer

You are probably over-complicating matters by using separate tables for message, message_text and location. Just merge them into one table:

message
-id
-type
-sender_id
-body
-latitude
-longitude

If the columns may not have values, be sure to set them to NULLable in the table definition.

There are various valid reasons for using one to one relationships, for example for example if you expect to have a lot of records with shorter fields in the primary table but then only occasionally need records with longer fields in the secondary table but in most cases they are not necessary and only serve to complicate your design which will require more joins it otherwise would not.

From the general tone of your question you seem to be new to database design and I doubt you really want to do this. Keep everything about the message in one table and then you can inherently only have one location, one body, etc.

IF you wanted to create a one-to-one relationship the usual way you would go about this would be to make the primary key on the secondary table also a foreign key referencing the primary table. So both tables would have the same primary key value for a given record- this would ensure you could only have one.

https://www.mkyong.com/mysql/how-to-define-one-to-one-relationship-in-mysql/

As it is now, you could have multiple records in these tables, a one-to-many relationship.

But I would strongly suggest you just merge into one table.

Your attachment and image tables look fine, that will be a one-to-many relationship with separate primary keys and linked using a foreign key.