Search code examples
phpmysqljoininner-join

How to get all data from 3 tables using a relationship/mapping table with foreign key


I have 2 tables with a 3rd mapping table that only have ids(foreign key) of the two tables. is it possible to get a result like this with just one query

╔═══════╦═══════╗
║user_id║ data  ║
╠═══════╬═══════╣
║   1   ║ {a, c}║
╠═══════╬═══════╣
║   2   ║   b   ║
╚═══════╩═══════╝

Table users:
    user_id (pk, fk to relationship.userid)

Table data:
    data_id (fk to data.data_id)
    data

Table relationship:
    user_id (fk of user.user_id)
    data_id (fk of data.data_id)

this is a sample data

USER
+-------+
|user_id|
|-------|
|   1   |
+-------+
|   2   |
+-------+

RELATIONSHIP
+-------+-------+
|user_id|data_id|
+-------+-------+
|   1   |   1   |
+-------+-------+
|   1   |   3   |
+-------+-------+
|   2   |   2   |
+-------+-------+

DATA
+-------+----+
|data_id|data|
+-------+----+
|   1   | a  |
+-------+----+
|   2   | b  |
+-------+----+
|   3   | c  |
+-------+----+

with the join query the result repeats user_id for each data it have similar to this How to get all data from 2 tables using foreign key

the problem with that is i am looping through the result in my php code to list users with all their datas once not multiple times for ever data the user have.


Solution

  • You can try group_concat() :

    SELECT r.user_id, group_concat(d.data)
    FROM relationship r
    JOIN data d ON r.data_id = d.data_id
    GROUP BY r.user_id;