2013-10-24 56 views
1

選擇來自其他表列,我有以下表的MySQL - 通過一個引用表

table "users" 
------------------------------ 
user_id name email 
------------------------------ 
1   joe  [email protected] 
2   jane [email protected] 
3   john [email protected] 

table "code_to_user_ref" 
--------------------------------- 
ref_id user_id code_id 
--------------------------------- 
1   1   1 
2   1   2 
3   2   3 
4   3   4 

table "codes" 
------------------ 
code_id code  
------------------ 
1   [email protected]$ 
2   [email protected]$5 
3   Vb#4%6 
4   Bn%6&8 

基本上,users表是我的所有註冊會員都。 codes表只是外部使用的有效激活碼列表。 code_to_user_ref表將每個用戶映射到他們擁有的代碼。

我想要做的就是呼應的表像這樣:

------------------------------ 
Name Email  Code/s owned 
------------------------------ 
joe  [email protected] [email protected]$, [email protected]$5 
jane [email protected] Vb#4%6 
john [email protected] Bn%6&8 

我怎麼會寫出這樣的查詢?

回答

3

嘗試這樣

SELECT A.Name,A.Email,GROUP_CONCAT(C.code) AS Codes owned 
     FROM users A,code_to_user_ref B,codes C 
     WHERE A.user_id = B.user_id 
     AND B.code_id=C.code_id 
GROUP BY A.user_id 
0
SELECT 
    Name, 
    Email, 
    (SELECT GROUP_CONCAT(code) FROM codes co 
     WHERE code_id in (SELECT code_id FROM code_to_user_ref c 
           WHERE c.user_id=u.user_id) 
    GROUP BY co.user_id) AS Codes owned 
FROM users u 
相關問題