r/DatabaseHelp • u/itsdeandre • Mar 21 '18
Basic DB question about foreign keys
OK. So I checked stackoverflow and there is a smilar question but it doesn't exactly help me understand my specific question and I'm hoping this sub can.
I'm working on a hobby project and am in the process of setting up a simply MySQL database.
There are 3 tables: users, questions, comments
I kind of understand the concept of foreign keys and how they work but something is confusing me. I have a user_id and question_id FK inside my comments table. Say user_id '123' adds a comment to question '456'. Now my comment table has a comment in it. I manually have to add '123' and '456' to my comment table each time. How does the comment table know it's '123' is linked to user_id
View all comments
Show parent comment
1
u/wolf2600 Mar 22 '18
You also don't HAVE to create FK relations between tables. Without them you could get orphaned records (comments where the user has been deleted, etc), but if that's okay in your case, then you can do it.
The way the DB knows that
user_id123 in Comments is the sameuser_id123 in Users is because when you query the database, you tell it explicitly in theJOINcontext:This will return all the comments for the user John Smith. The
onclause in theinner joinspecifies how to relate the Users and Comments tables, and that it is to join records where the Usersuser_idvalue is the same as the Commentsuser_idvalue. And then thewhereclause limits the records to only those where the Users.name value is 'John Smith'.In this example, you can either setup your schema with FK relationships or without. The query will still run the same. The only thing specifying the FK relationship when you build the tables does is prevent you from inserting a record into Comments with user_id value of 123 when there isn't already a record in Users with user_id value of 123.