具有条件

时间:2015-08-17 11:58:26

标签: 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        |
+----------+----------+

现在我想要显示这样的内容(只有Peter Pan成员的组,因为Peter Pan实际登录了):

+----+------------+--------------+---------------------+--------------+
| id | group name | group desc   | group members       | group games  |
+----+------------+--------------+---------------------+--------------+
|  1 | GroupName1 | Description1 | Peter Pan, Bob Fred | Game1, Game2 |
+----+------------+--------------+---------------------+--------------+

这是我的查询(我使用预处理语句,而?将是用户的用户ID)

SELECT
    g.group_name,
    g.group_id,
    g.group_desc,
    GROUP_CONCAT(DISTINCT u.realname SEPARATOR ', ') AS users,
    GROUP_CONCAT(DISTINCT ga.game SEPARATOR ', ') AS games
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 AND 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

我的查询不起作用,因为它列出了所有组,而不仅仅是实际用户所在的组。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

如果您希望组中包含用户的用户作为成员,请删除left join中用户的条件并添加:

HAVING MAX(u.user_id = ?) > 0

这只返回具有给定成员的组。

注意:您可能也不需要LEFT JOIN。故事应该具有适当的外键关系,并且需要至少有一个成员(有问题的用户)。