views:

59

answers:

1

Have 2 tables with a linking table between then.


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 1 query? I would like to be able to do that in MySQL, and POSTgreSQL - but I'll take whatever I can get!! Thanks

+2  A: 

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:

Mark Byers
Thank you very much for the answer. Although, i'm still looking for a postgresql answer - this was as close as I got:http://mssql-to-postgresql.blogspot.com/2007/12/cool-groupconcat.html
Nate Atkinson
thank you thank you, I've got the postgre answer, I didn't see your link at first
Nate Atkinson