MySQL - 通过引用表从另一个表中选择列

时间:2013-10-24 06:11:49

标签: php mysql reference

我有以下表格

table "users"
------------------------------
user_id    name    email
------------------------------
1          joe     joe@doe.com
2          jane    jane@doe.com
3          john    john@doe.com

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          xC1@3$
2          Cv@3$5
3          Vb#4%6
4          Bn%6&8

基本上,users表是我所有注册会员的所在地。 codes表只是外部使用的有效激活码列表。 code_to_user_ref表将每个用户映射到他们拥有的代码。

我想要做的是回复一个像这样的表:

------------------------------
Name    Email     Code/s owned
------------------------------
joe     joe@...   xC1@3$, Cv@3$5
jane    jane@...  Vb#4%6
john    john@...  Bn%6&8

我如何写出这样的查询?

3 个答案:

答案 0 :(得分:6)

尝试:

    SELECT a.name,a.email, GROUP_CONCAT(c.code)
      FROM users a 
      JOIN code_to_user_ref b ON a.user_id = b.user_id
      JOIN codes c ON b.code_id = c.code_id 
  GROUP BY a.name,a.email

结果将是:

| NAME |        EMAIL |  CODE/S OWNED |
|------|--------------|---------------|
| jane | jane@doe.com |        Vb#4%6 |
|  joe |  joe@doe.com | Cv@3$5,xC1@3$ |
| john | john@doe.com |        Bn%6&8 |

这是SQLFiddle

答案 1 :(得分: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

答案 2 :(得分: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