我正在尝试一个简单的(或不是)查询来获取存在于2个部门中的用户。
STRUCT:
用户 ID 名称
UserDepartment ID ID用户 IDDepartment
系 ID 名称
所以我想要来自DepartmentA和DepartmentB的用户(
不可能这样做:
Select * from User as US
left join UserDepartment as DP on User.ID = UserDepartment.IDUser
where DP.IDDepartment = 1 and DP.IDDepartment = 2
零结果......
解决此问题的查询类似于:
select * from UserDepartment
where IDDepartment in (1,2)
group by IDUser
having COUNT(*)=2
但这是唯一的解决方案吗?还有其他简单的疑问吗?
答案 0 :(得分:1)
获取属于1和2部门的所有用户:
SELECT *
FROM User
WHERE User.ID IN (SELECT UserID FROM UserDepartment WHERE IDDepartment = 1)
AND User.ID IN (SELECT UserID FROM UserDepartment WHERE IDDepartment = 2)
结果与后面的查询基本相同,只是它专门查找同时位于" 1"和" 2",而不是任何有2个或更多部门记录属于" 1"或" 2" (不包括有两个" 1"记录但没有" 2"记录的人。
如果您希望在结果中包含来自userdepartment表的信息,只需将其更改为:
SELECT *
FROM User US
INNER JOIN (SELECT * FROM UserDepartment WHERE IDDepartment IN(1,2)) DP ON US.ID = DP.UserID
WHERE User.ID IN (SELECT UserID FROM UserDepartment WHERE IDDepartment = 1)
AND User.ID IN (SELECT UserID FROM UserDepartment WHERE IDDepartment = 2)
答案 1 :(得分:1)
这似乎是 INTERSECT 的工作。您可以通过以下操作获取所需的用户ID列表:
SELECT IDUser FROM UserDepartment WHERE IDDepartment = 1
INTERSECT
SELECT IDUser FROM UserDepartment WHERE IDDepartment = 2
答案 2 :(得分:0)
/*** If only users for dept 1 and 2 need to be shown the use this query ****/
Select * from #User u
inner join
(
Select d1.UserID from #UserDepartment d1
where d1.Department = 1
intersect
Select d2.UserID from #UserDepartment d2
where d2.Department = 2
except
Select d2.UserID from #UserDepartment d2
where d2.Department not in (1,2)
)t on u.ID = t.UserID
/***If the users that belong to dept 1 and 2 and can exist in
other depts then use this one**/
Select * from #User u
inner join
(
Select d1.UserID from #UserDepartment d1
where d1.Department = 1
intersect
Select d2.UserID from #UserDepartment d2
where d2.Department = 2
)t on u.ID = t.UserID
/**To test use the following commented code**/
/*Select * into #User from
(
Select 1 as ID, 'A' as Name
union
Select 2,'B'
union
Select 3,'C'
union
Select 4,'D'
union
Select 5,'E'
union
Select 6,'F'
union
Select 7,'G'
union
Select 8,'H'
union
Select 9,'I'
union
Select 10,'G'
)t
Select * into #Department from
(
Select 1 as ID, 'D1' as Name
union
Select 2,'D2'
union
Select 3,'D3'
union
Select 4,'D4'
)t2
Select * into #UserDepartment from
(
Select 1 AS ID ,1 AS UserID ,1 AS Department
union
Select 2,1,2
union
Select 3,1,3
union
Select 4,2,1
union
Select 5,3,2
union
Select 6,4,1
union
Select 7,4,2
)t3
*/