简体   繁体   中英

MySQL how to link tables

I am trying to create a to do web app using mysql. Can someone explain how I can select the todos specific for one user? How do I link the users table with the todos table? General advice would be preffered, not actual code.

It is called a foreign key relation . It goes like this

users table
-----------
id (auto increment primary key)
name
address
...


todos table
-----------
id (auto increment primary key)
user_id (id from users table - this is the foreign key and relation to the user)
todo_text
...

If you want to select the todos of a user later then you can use a join:

select todos.*
from todos
inner join users on users.id = todos.user_id
where users.name = 'john'

You would link them by id's

So if you have two tables (UserTable) and (ToDoTable) you would get the todos with a select like this.

Select * from ToDoTable where ToDoTable.user_id = 1;

That query is essentially saying give me everything from the todotable where the user is bob (since bob has a primary key id of 1)

The user table will have users like :

Name | id  
Bob    1  
John   2  

and the TodoTable will have

Task           |  user_id  
Clean dishes        2   
Take out Trash      1  

That way we link the tasks to the user table by the user_id
The User table will have a primary key (id)
and it is referenced on the todo table as a foreign key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM