Nate Atkinson
Nate Atkinson

Reputation: 535

In a single mysql query, select multiple rows from one table, each containing multiple rows from a linking table

Have two tables with a linking table between them.


USERS
+-------+---------+
| userID| Username|
+-------+---------+
|     1 |  Nate   | 
|     2 |  Nic    | 
|     3 |  John   | 
+-------+---------+

SITES
+--------+---------+
| siteID | Site    |
+--------+---------+
|     1  |  art    | 
|     2  |  com    | 
|     3  |  web    | 
+--------+---------+

USER_SITES
+-------------+---------+---------+
| user_site_id| user_id | site_id |
+-------------+---------+---------+
|     1       |  1      | 1       |
|     2       |  1      | 2       |
|     3       |  1      | 3       |
|     4       |  2      | 2       |
|     5       |  2      | 3       |
+-------------+---------+---------+

I want to do one query that will output like this


USERS
+---------+----------------+
| username| sites          |
+---------+----------------+
|  Nate   |  art, com, web | 
|  Nic    |  com, web      | 
+---------+----------------+

Can that be done easily with one query? I would like to be able to do that in MySQL, and POSTgreSQL - but I'll take whatever I can get!

Upvotes: 1

Views: 1148

Answers (1)

Mark Byers
Mark Byers

Reputation: 838346

It can be done in MySQL using GROUP_CONCAT:

SELECT
    username,
    GROUP_CONCAT(Site ORDER BY Site SEPARATOR ', ') AS sites
FROM USER_SITES
JOIN USERS ON USER_SITES.user_id = USERS.userID
JOIN SITES ON USER_SITES.site_id = SITES.siteID
GROUP BY username

Result:

+---------------------------+
| username  | sites         |
+---------------------------+
| Nate      | art, com, web |
| Nic       | com, web      |
+---------------------------+

To see how to emulate GROUP_CONCAT in PostgreSQL see this question:

Upvotes: 2

Related Questions