Mysql group_concat具有多对多的关系

时间:2014-04-30 13:43:58

标签: php mysql sql

我有三张桌子

+-------------+  +-----------------------------+  +-----------+
| WORKSPACES  |  | USERS_WORKSPACES            |  | USERS     |
+-----+-------+  +----+---------+--------------+  +----+------+
| id  | title |  | id | user_id | workspace_id |  | id | name |
+-----+-------+  +----+---------+--------------+  +----+------+
|  1  |  W1   |  | 1  |   1     |     1        |  |  1 |  U1  |
|  2  |  W2   |  | 2  |   1     |     2        |  |  2 |  U2  |
|  3  |  W3   |  | 3  |   2     |     2        |  |  3 |  U3  |
+-----+-------+  +----+---------+--------------+  +----+------+

我尝试查询数据库以列出给定user_id的唯一工作空间。对于返回的每个工作空间,我想要一组唯一的用户ID。像这样:

对于user_id = 2

+--------------+-----------------+-------+
| workspace_id | workspace_title | users |
+----------------------------------------+
| 1            | W1              | 1     |
+----------------------------------------+
| 2            | W2              | 1,2   |
+----------------------------------------+

对于user_id = 2

+--------------+-----------------+-------+
| workspace_id | workspace_title | users |
+----------------------------------------+
| 2            | W2              | 1,2   |
+----------------------------------------+

通过此查询,我可以列出所有工作区的唯一用户ID。如何将列表限制为仅与指定user_id关联的工作空间?

SELECT w.id,
       w.title,
       group_concat(b.user_id) as users
FROM   workspaces w, 
       users_workspaces b,
       users u
WHERE  w.id = b.workspace_id 
  AND  b.user_id = u.id
GROUP BY w.id

2 个答案:

答案 0 :(得分:2)

您的查询功能正常。但是,您无需加入users表,因为您可以从user_id获取users_workspaces。而且,您应该使用正确的连接语法:

select w.id, w.title, group_concat(uw.user_id) as users
from workspaces w join 
     users_workspaces uw
     on w.id = uw.workspace_id 
group by w.id;

如果要将此限制为与特定用户ID关联的工作空间,请使用having子句:

select w.id, w.title, group_concat(uw.user_id) as users
from workspaces w join 
     users_workspaces uw
     on w.id = uw.workspace_id 
group by w.id
having sum(uw.user_id = @USERID) > 0;

答案 1 :(得分:0)

试试这个 - 您可以在where子句中替换user_id的任何值或变量:

SELECT
w.id,
w.title,
group_concat(b.user_id) as users
FROM 
workspaces w 
JOIN users_workspaces b ON w.id = b.workspace_id 
JOIN users u ON b.user_id = u.id
where 
u.user_id = 2 
group by w.id