I used an online SQL builder to help design some MySQL tables I’m working on. Foreign keys always confuse me.
The code I came up with tries to add these 4 foreign keys but I want to make sure that I want them before I add them.
ALTER TABLE `users` ADD FOREIGN KEY (user_id) REFERENCES `settings` (`user_id`);
ALTER TABLE `logins` ADD FOREIGN KEY (user_id) REFERENCES `users` (`user_id`);
ALTER TABLE `mail_threads` ADD FOREIGN KEY (folder_id) REFERENCES `mail_folders` (`folder_id`);
ALTER TABLE `mail_message` ADD FOREIGN KEY (thread_id) REFERENCES `mail_threads` (`thread_id`);
So basically what will to limit me from doing? All 4 of these tables below, I need to be able to update individually without them messing with the other, so should I not use a foreign key on them?
Foreign Keys are a way for the database to assign an association to a ‘parent’ table.
I’ll start from the bottom of your list and work my way up.
The bottom FK states that the column
mail_message.thread_idis a reference tomail_threads.thread_idThe next FK states that the column
mail_threads.folder_idis a reference tomail_folders.folder_idWhat this means is that a mail_thread “belongs to” a mail_folder, and a mail_message “belongs to” a mail_thread. So if you have no mail_thread with a thread_id of 20 you can not create a mail_message with a thread_id of 20, because it wouldn’t make any sense (and the reference wouldn’t function). It also prevents you from deleting a mail_thread of say thread_id 20 if there are messages within that thread without either cascading the delete (forcing the deletion of everything associated through the constraints) or deleting the messages first.
In a nutshell, those two constraints say:
mail_messages belong to mail_threads which belong to mail_folders
-or-
mail_folders have zero to many mail_threads which have zero to many mail_messages
SO Question with the benefits/pitfalls of FKs:
What's wrong with foreign keys?