在单个mysql查询中,从一个表中选择多个行,每个行包含一个链接表中的多个行

时间:2010-09-10 19:45:54

标签: php mysql postgresql

有两个表,它们之间有一个链接表。


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

我想做一个像这样输出的查询


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

一次查询可以轻松完成吗? 我希望能够在MySQL和POSTgreSQL中做到这一点 - 但我会尽我所能!

1 个答案:

答案 0 :(得分:2)

可以使用GROUP_CONCAT在MySQL中完成:

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

结果:

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

要了解如何在PostgreSQL中模拟GROUP_CONCAT,请看这个问题: