簡體   English   中英

MySQL如何鏈接表

[英]MySQL how to link tables

我正在嘗試使用mysql創建一個Web應用程序。 有人可以解釋我如何選擇特定於一個用戶的待辦事項嗎? 如何將users表與todos表鏈接? 一般建議將是優先的,而不是實際的代碼。

它被稱為外鍵關系 它是這樣的

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
...

如果您想稍后選擇用戶的待辦事項,則可以使用連接:

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

你可以通過id鏈接它們

因此,如果您有兩個表(UserTable)和(ToDoTable),您將獲得這樣的選擇todos。

Select * from ToDoTable where ToDoTable.user_id = 1;

該查詢基本上是說從用戶是bob的todotable給我一切(因為bob的主鍵id為1)

用戶表將具有以下用戶:

Name | id  
Bob    1  
John   2  

和TodoTable將有

Task           |  user_id  
Clean dishes        2   
Take out Trash      1  

這樣我們就可以通過user_id將任務鏈接到用戶表
User表將具有主鍵(id)
它在todo表上作為外鍵引用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM