如何在组/用户关系中联接表?

时间:2018-08-02 17:48:18

标签: sql postgresql

问题: 选择具有id = 1的用户为管理员的所有组,以及同一用户所属的所有组(不包括重复项)。您可以成为群组管理员,而不必属于该群组。

架构:

users table
id, name

groups table
id, name, admin_id (user_id)

group_members table
group_id, member_id

SQL查询:

SELECT groups.name as group_name,
users.id as user_id,
users.name as user_name
FROM groups
INNER JOIN users ON groups.admin_id = users.id and users.id=1
LEFT JOIN group_members ON group_members.group_id = groups.id
LEFT JOIN users as users2 on group_members.member_id = users2.id and users2.id=1;

当前结果

http://sqlfiddle.com/#!17/a3158/26

更新1 编辑以指示查询针对的是ID = 1的单个用户

2 个答案:

答案 0 :(得分:1)

select distinct member_id, group_id from group_members 
where member_id in(select admin_id from groups) 
order by member_id, group_id

我认为实现所需的result ...

并不一定是必需的。

在这里使用joins提取用户名/组名。

select distinct m.member_id, u.name, m.group_id, g.name 
from group_members m
left join users u
on member_id = u.id
left join groups g
on group_id = g.id
where m.member_id in(select admin_id from groups) 
order by member_id, group_id

答案 1 :(得分:1)

  

选择具有id = 1的用户为管理员的所有组,以及该用户所属的所有组(不包括重复项)

两种解决方案:

SELECT g.id AS group_id, g.name AS group_name
FROM   groups g
WHERE (g.admin_id = 1
OR     EXISTS (
        SELECT FROM group_members gm
        WHERE gm.group_id = g.id
        AND   gm.member_id = 1));

或者:

SELECT id AS group_id, name AS group_name
FROM   groups
WHERE  admin_id = 1

UNION
SELECT g.id, g.name
FROM   group_members gm
JOIN   groups        g ON g.id = gm.group_id
WHERE  gm.member_id = 1;

http://sqlfiddle.com/#!17/563da/10以您为基础。