1

我有以下表格

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

我将如何写出这样的查询?

4

3 回答 3

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

于 2013-10-24T06:19:36.130 回答
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
于 2013-10-24T06:17:00.600 回答
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
于 2013-10-24T06:26:53.507 回答