LEFT JOIN与多个表

时间:2015-08-16 22:09:06

标签: mysql

我有以下表格:

table users - PRIMARY KEY (user_id)
+---------+----------+-----------+
| user_id | username | realname  |
+---------+----------+-----------+
|       1 | peterpan | Peter Pan |
|       2 | bobfred  | Bod Fred  |
|       3 | sallybe  | Sally Be  |
|       6 | petersep | Peter Sep |
+---------+----------+-----------+

table users_groups - PRIMARY KEY (user_id, group_id)
+---------+----------+
| user_id | group_id |
+---------+----------+
| 1       | 1        |
| 1       | 2        |
| 2       | 1        |
| 2       | 2        |
| 3       | 6        |
| 3       | 9        |
| 6       | 6        |
| 6       | 9        |
+---------+----------+

table game - PRIMARY KEY (id)
+----+-------+
| id | game  |
+----+-------+
| 1  | Game1 |
| 2  | Game2 |
| 6  | Game6 |
| 9  | Game9 |
+----+-------+

table groups - PRIMARY KEY(group_id)
+----------+--------------+---------------+
| group_id | group_name   | group_desc    |
+----------+--------------+---------------+
| 1        | Groupname1   | Description1  |
| 2        | Groupname2   | Description2  |
+----------+--------------+---------------+

table group_game - PRIMARY KEY(group_id, game_id)
+----------+----------+
| group_id | game_id  |
+----------+----------+
| 1        | 1        |
| 1        | 2        |
| 2        | 6        |
| 2        | 9        |
+----------+----------+

我想显示此内容(如组列表):

+----+------------+--------------+---------------------+--------------+
| id | group name | group desc   | group members       | group games  |
+----+------------+--------------+---------------------+--------------+
|  1 | GroupName1 | Description1 | Peter Pan, Bob Fred | Game1, Game2 |
|  2 | GroupName2 | Description2 | Sally Be, Peter Sep | Game6, Game9 |
+----+------------+--------------+---------------------+--------------+

现在我有了这个查询,但它没有给我任何行(没有错误,只有零行):

SELECT
    g.group_name,
    g.group_id,
    g.group_desc,
    GROUP_CONCAT(DISTINCT ga.game SEPARATOR ', ') AS games,
    GROUP_CONCAT(DISTINCT u.realname SEPARATOR ', ') AS users
FROM groups g
LEFT JOIN users_groups ug1
    ON g.group_id=ug1.group_id
LEFT JOIN users u
    ON ug1.user_id=u.user_id
LEFT JOIN group_game gg
   ON g.group_id=gg.group_id
LEFT JOIN game ga
   ON gg.game_id=ga.id
GROUP BY g.group_name

如何解决此问题或如何编写此查询?

我只想显示包含所有信息的群组列表(例如群组信息,群组用户,此群组的游戏)。

0 个答案:

没有答案