简体   繁体   中英

MySQL - Select column from another table via a reference table

I have the following tables

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

Basically, the users table is where all my registered members are. The codes table is just a list of valid activation codes for use externally. The code_to_user_ref table maps each user to the code/s that they own.

What I want to do is echo a table like so:

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

How would I write out a query for such?

Try:

    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

The result would be:

| 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 |

Here's the SQLFiddle .

Try like this

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM