MySQL只返回指定组中的用户
在MySql数据库中,我有一个相当常见的用户和组,其中有一个pivot users\u groups来允许N:M关系 表MySQL只返回指定组中的用户,mysql,pivot-table,group-concat,Mysql,Pivot Table,Group Concat,在MySql数据库中,我有一个相当常见的用户和组,其中有一个pivot users\u groups来允许N:M关系 表用户 id | name --------+---------- 1 | Joe 2 | Anna 3 | Max 表组 id | name ---------+---------- 1 | Red 2 | Blue 3 | Green id | userid |
用户
id | name
--------+----------
1 | Joe
2 | Anna
3 | Max
表组
id | name
---------+----------
1 | Red
2 | Blue
3 | Green
id | userid | groupid
---------+--------+---------
1 | 1 | 2
2 | 3 | 2
3 | 1 | 3
3 | 2 | 1
表用户组
id | name
---------+----------
1 | Red
2 | Blue
3 | Green
id | userid | groupid
---------+--------+---------
1 | 1 | 2
2 | 3 | 2
3 | 1 | 3
3 | 2 | 1
所以。。。红色(1)组的成员是安娜(2),绿色(3)组的成员是乔(1),蓝色(2)组的成员是乔(1)和马克斯(3)
当用户登录时,我有用户id(例如,Joe为1),我想查找我的登录用户也是其成员的特定组中的所有其他用户。如何获取该组中的用户列表
我需要使用表单提供的文本查找组名,用户ID将从身份验证/登录代码中获得。如果用户不是组的一部分,则他们将无法获取组成员的列表
对于红色组,当以Anna身份登录时,我应该只看到一个用户(Anna)
User | Group | Users in Group must include the current user
------+------------
1 | Red | EMPTY
User | Group | Users in Group must include the current user
------+------------
2 | Red | Anna
User | Group | Users in Group must include the current user
------+------------
3 | Red | EMPTY
对于Blue group,如果我以Joe或Max的身份登录,那么我将看到一个用户列表(Joe和Max)
对于Green组,当作为Joe登录时,我应该只看到一个用户(Joe)
User | Group | Users in Group must include the current user
------+------------
1 | Green | Joe
User | Group | Users in Group must include the current user
------+------------
2 | Green | EMPTY
User | Group | Users in Group must include the current user
------+------------
3 | Green | EMPTY
==更新#1===
使用@Erico的答案和下面的fiddle以及更新的表模式来包括enabled和email字段,我可以通过额外的enabled
列检查来执行以下操作。但是,我希望将所有用户作为结果集中的单独行返回,而不是返回一个包含所有数据的Users
列
==更新#2===
不是在一行中返回结果,而是:
User | Group | Users in Group must include the current user
------+------------
1 | Blue | Joe, Max
或者用电子邮件代替名字
User | Group | Users in Group must include the current user
------+------------
1 | Blue | joe@mycompany.com, max@hiscompany.com
我希望每个用户返回一行中的用户完整信息,因此在蓝色组(2)中搜索用户Joe(1)将返回:
User | Name | Email
------+------------
1 | Joe | joe@mycompany.com
3 | Max | max@hiscompany.com
下面是一个包含子查询的示例,该子查询显示问题中显示的结果
乔·肖文宁集团蓝色:
SELECT '1' as `User`, name as `Group`,
(SELECT GROUP_CONCAT(name) FROM users u, users_groups ug
WHERE u.id = ug.user_id AND ug.group_id = g.id
AND ug.group_id IN (SELECT group_id FROM users_groups WHERE user_id = 1)
) as `Users`
FROM groups g
WHERE g.name = 'Blue'
这是一种享受,谢谢你的拨弄。还有一个请求—如果匹配失败,我如何不返回任何行—当前始终返回一行,其中包含正确的用户列表或NULL。如果Users
中返回NULL,我想返回一个空集。这个fiddle对我的实际表设计更为具体,我还想检查每个用户和每个组的启用标志,并且只返回启用组中启用用户的结果。另外,我想返回Users
result列中的电子邮件地址,而不是用户名。如果我自己解决,我会把答案贴出来。这是小提琴:。刚刚在主查询中添加了启用标志和移动的用户/组条件,这样当它不匹配任何组时就不会返回任何行。最后一件事是,如何按每个用户返回一行中的用户,而不是只返回一行中的用户?请参阅原始问题的更新#2。