2012-05-17 27 views
1

可能是你能幫助我:MYSQL要求

我有一個表:

1: Users 
id username email 
1 myname  [email protected] 
2 myname2 [email protected] 

2: Accounts 
user_id account 
1   37992054 
2   3804933 
1   23286966 

我需要做的請求,並得到這樣的數據:

id username email    account 
1 myname  [email protected] 37992054, 23286966 
2 myname2 [email protected] 3804933 
+1

瞭解[SQL連接(http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins的.html)。您需要使用帶有「GROUP BY」子句的['GROUP_CONCAT()'](http://dev.mysql.com/doc/en/group-by-functions.html#function_group-concat)。 – eggyal

回答

4

你需要加入你的兩個表並使用分組構造來摺疊具有相同用戶ID的記錄:

Select u.id, u.username, u.email, group_concat(a.account) 
from users as u join accounts as a 
    on a.user_id = u.id 
group by u.id; 
+0

偉大的解決方案D Mac。大拇指!你知道如何去相反嗎?假設我們將結果插入到一個新表中。我們怎樣才能使用這些逗號分隔列來得到結果作爲賬戶表? –

+0

太棒了!感謝它的工作。 – user889349

0

你需要一個標準的連接查詢:

select u.id,u.username,u.email,a.account from Users as u, Accounts as a where u.id=a.id;