[英]MySQL how to link tables
I am trying to create a to do web app using mysql. 我正在尝试使用mysql创建一个Web应用程序。 Can someone explain how I can select the todos specific for one user? 有人可以解释我如何选择特定于一个用户的待办事项吗? How do I link the users table with the todos table? 如何将users表与todos表链接? 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 你可以通过id链接它们
So if you have two tables (UserTable) and (ToDoTable) you would get the todos with a select like this. 因此,如果您有两个表(UserTable)和(ToDoTable),您将获得这样的选择todos。
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) 该查询基本上是说从用户是bob的todotable给我一切(因为bob的主键id为1)
The user table will have users like : 用户表将具有以下用户:
Name | id
Bob 1
John 2
and the TodoTable will have 和TodoTable将有
Task | user_id
Clean dishes 2
Take out Trash 1
That way we link the tasks to the user table by the user_id 这样我们就可以通过user_id将任务链接到用户表
The User table will have a primary key (id) User表将具有主键(id)
and it is referenced on the todo table as a foreign key 它在todo表上作为外键引用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.