2014-03-07 39 views
0

我想創建一個使用mysql做web應用程序。有人可以解釋我如何選擇特定於一個用戶的待辦事項嗎?如何鏈接用戶表和todos表?一般建議將被優先考慮,而不是實際的代碼。MySQL如何鏈接表

回答

2

它被稱爲外鍵關係。它是這樣的

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' 
+0

非常感謝您!但我還有一個問題。例如,如何獲得'john'作爲當前登錄的用戶,以便將任務插入特定用戶的表中?我需要一個變量嗎? – user3143696

+0

我不太清楚你的要求。最好問一個新問題。您對這個新問題所提供的信息越多,得到準確答案的速度就越快。添加代碼總是很好的。祝你好運。 –

0

你會通過ID的

所以,如果你有將它們鏈接兩個表格(UserTable)和(ToDoTable),你會得到一個選擇像這樣的待辦事項。

Select * from ToDoTable where ToDoTable.user_id = 1; 

該查詢基本上等於在說給我一切從用戶所在鮑勃todotable(因爲鮑勃具有1的主鍵ID)

用戶表將用戶喜歡的:

Name | id 
Bob 1 
John 2 

和TodoTable將有

Task   | user_id 
Clean dishes  2 
Take out Trash  1 

這樣,我們鏈接的任務TH E用戶表由USER_ID
用戶表將有一個主鍵(id)
,它是在待辦事項表中引用的外鍵