如何检索将使用第一个子查询匹配所有行的记录

时间:2011-10-20 11:38:15

标签: sql postgresql

您需要帮助解决一些复杂的查询。我将输入用户名(比如test)发送给查询。我必须列出具有相同角色的用户名测试的其他用户,并且这些用户名应该与用户名测试的所有groupid匹配。如果其他用户拥有的组多于用户名测试不是问题,但应该匹配用户名测试中存在的所有groupdid。我尝试了以下查询。如果所有groupid匹配,它将不返回任何行。但是,我需要那些与所有组ID匹配的用户名,而不是为完全匹配不返回任何行。

select 
  group_id 
from 
  user_info us ,group_privilege_details gp 
where 
  login_name='test' 
  and us.user_id = gp.user_id 
EXCEPT
select 
  group_id 
from 
  user_info u ,group_privilege_details g 
where login_name !='test' 
and role_id in (select role_id 
                from user_info 
                where login_name ='test')
and group_id in (select group_id 
                 from user_info us ,group_privilege_details gp 
                 where login_name='test' 
                 and us.user_id = gp.user_id ) 
and g.user_id = u.user_id

提前致谢。很抱歉很长的解释

1 个答案:

答案 0 :(得分:3)

如果我理解你想要:

select all users,
        not being user test,
        with same role as user test,
        where not exists a group where user test is a member of
            and the other user is not a member of

在SQL中,类似于以下内容。我使用了以下缩写:OU其他用户,TU测试用户,TUG测试用户组,OUG其他用户组。

select OU.login_name, OU.user_id
    from user_info OU, user_info TU
    where OU.user_id <> TU.user_id 
        and OU.role_id = TU.role_id 
        and TU.login_name = 'test'
        and not exists (
            select * from group_privilege_details TUG
                where TUG.user_id = TU.user_id
                    and TUG.group_id not in (
                        select group_id 
                            from group_privilege_details OUG 
                            where OUG.user_id = OU.id
                    )
        )