请帮忙查询sql

时间:2013-11-19 09:02:09

标签: sql sql-server sql-server-2008

select 
u.username 
from users u join userrole ur on u.userid= ur.userid 
where  username in
                    ( 
                        select 
                            username 
                            from users u join userrole ur on u.userid= ur.userid 
                            join roles r on ur.roleid=r.roleid 
                            where r.active=1 
                            and u.active=1 
                            and ur.active=1 
                            and ur.roleid in (1,2,3,4)
                    )
r.active=1 and u.active=1 and ur.active=1 

用户ID在用户角色表中具有不同的角色需要userid分配roleid 1,2,3,4

例如,用户A具有1,2,3,4,5,100个角色,它不应该只显示用户已分配1,2,3,4。

2 个答案:

答案 0 :(得分:0)

最终解决方案,虽然这是一个繁重的查询,但我只能找到以下解决方案

select distinct(u.username) 
from 
users u
join 
userrole ur 
on 
u.userid= ur.userid 
join
roles r
on
ur.roleid=r.roleid
where  
r.active=1 
and 
u.active=1 
and 
ur.active=1 
and 
ur.userid in (select userid from userrole where roleid = 1)
and ur.userid in (select userid from userrole where roleid = 2)
and ur.userid in (select userid from userrole where roleid = 3)
and ur.userid in (select userid from userrole where roleid = 4)

您可以在http://sqlfiddle.com/#!3/25dd8/1

查看工作解决方案

用户表

enter image description here

userrole table

enter image description here

角色表

enter image description here

查询输出

enter image description here

答案 1 :(得分:0)

try this

   select username from users u
                           inner join userrole ur on u.userid= ur.userid 
                           inner join roles r on ur.roleid=r.roleid 
where r.active=1 and u.active=1 and ur.active=1 and  r.active=1 and u.active=1 and ur.active=1 
and ur.roleid in ('1','2','3','4')