日期:2014-05-18  浏览次数:20483 次

sql表多对多的查询
现在有一张用户表 user
id,name
 1 lu
 2 ren
 3 si


角色表 role

id,roleName
1 ,普通
2,管理员


中间表

userid ,roleid
1 , 1

1 , 2

2 , 1

2 , 2
3 , 1



现在要查询同时 是普通和管理员角色的用户 ,注: 中间表现在有1000W条记录

查询语句应该如何写




------解决方案--------------------
SQL code

select user.id,user.name from user 
where user.id in(
   select userid,count(roleid) from 中间表
where count(roleid)>1 group by userid);

--等大牛

------解决方案--------------------
role--有多个角色时把加条件加上b.roleName in('普通','管理员')
SQL code
select * from  [user] as a where not exists(select 1 from [role]  as b where b.roleName in('普通','管理员') and  not exists(select 1 from 中间表 where userID=a.userID and roleID=b.roleID))

------解决方案--------------------
SQL code
select distinct a.name 
from [user] a inner join 中间表 b on a.id=b.userid
inner join [role] c on c.id=b.roleid
inner join [role] d on d.id=b.roleid
where c.roleName='普通' and d.roleName='管理员'