3

我有表Users

我也有表Departments

我在Users和之间有一个地图表Departments

我想找到所有部门中出现的所有用户ID 。

例如,如果有 5 个部门,而 Paul 仅在部门 #1 中,那么 Paul 将不会出现在输出列表中。

只有当他被列在所有部门中时,他才会 (1..5)

我开始使用临时表做一些很长(很长)的事情,我认为有更好的方法。

我还创建了一个Sql Fiddle

4

6 回答 6

1

试试这个

SELECT u.userId, u.UserName 
FROM MapUserstoDepartments m INNER JOIN
     Users u ON u.userId = m.userId
GROUP BY u.userId, u.UserName 
HAVING COUNT(m.depId) = (SELECT COUNT(*) FROM Departments)

那会产生

| USERID | USERNAME |
---------------------
|    100 |     John |

sqlfiddle

于 2013-02-15T10:22:15.387 回答
1

有不止一种方法可以做到这一点。

您可以要求用户所在的部门数等于部门总数:

SELECT
    * 
FROM
    Users
    INNER JOIN 
    (
        SELECT userId, COUNT(*) c FROM MapUserstoDepartments
        GROUP BY userId
        HAVING COUNT(*) = (SELECT COUNT(*) FROM Departments)
    ) UsersInAllDepartments
    ON Users.userId = UsersInAllDepartments.userId

您可以要求从所有部门列表中删除用户的部门:

SELECT * 
FROM Users
WHERE NOT EXISTS 
  (
    SELECT depId FROM Departments
    EXCEPT
    SELECT depId FROM MapUserstoDepartments WHERE userId = Users.userId
  )

我确定还有其他人。

于 2013-02-15T10:26:54.913 回答
1

你可以这样做:

select  u.* 
from    Users u
where not exists
(
    select  1 
    from    Departments d 
    where   not exists
    ( 
      select  1 
      from    MapUserstoDepartments m 
      where   d.depId = m.depId
      and     m.userId = u.userId
     )
)

SQL小提琴

于 2013-02-15T10:27:27.127 回答
0

这是你想要的吗?

Select Tbl.userID , Tbl.username from (Select u.userid , u.username ,  
count(u.userid)  as Count from MapUsersToDepartments m
inner join Users u on m.UserID = u.userID
group by u.userid , u.username)Tbl
where Tbl.Count = (Select count(*) from Departments)

这是小提琴

http://sqlfiddle.com/#!3/5a960/53

于 2013-02-15T10:19:16.003 回答
0
select
  Users.userId,
  count(Departments.depId),
  count(MapUserstoDepartments.userId)

from
  Users
  left join MapUserstoDepartments on MapUserstoDepartments.userId = Users.userId
  left join Departments on Departments.depId = MapUserstoDepartments.depId


group by 
  Users.userId

having
  (SELECT COUNT(*) from Departments) = count(MapUserstoDepartments.userId)
于 2013-02-15T10:26:37.957 回答
0

试试下面的查询。让我知道这是否有帮助

 select * from users where userid in
       (select userid from MapUserstoDepartments
       group by userid
        having count(userid) = 5)
于 2013-02-15T10:40:50.847 回答