问题描述
我有两个sql Views公开与实体/分类配对有关的数据,另一个sql Views公开用户分类配对。
为了使用户有权访问实体,该用户必须具有分配给该实体的所有类别。所以:
EntityID ClassificationID
1 1
1 2
2 1
2 2
2 3
UserID ClassificationID
100 1
100 2
100 4
101 1
101 2
101 3
在上述情况下,用户100可以访问实体ID 1,但是用户101可以访问实体1和2。
我希望能够在这样的表中返回这些数据,本质上是授权和有权访问它们的用户的完整列表:
UserID EntityID
100 1
101 1
101 2
实现此目标的最佳方式和最佳方式是什么?我正在使用sql Server 2019
解决方法
这是一个关系划分问题。我建议使用联接来关联用户和实体,然后进行聚合,并使用having
子句进行过滤,以仅保留“完整”组。
假设这些表分别称为entities
和users
:
select u.userid,e.entityid
from entities e
inner join users u on u.classificationid = e.classificationid
group by u.userid,e.entityid
having count(*) = (select count(*) from entities e1 where e1.entityid = e.entityid)
userid | entityid -----: | -------: 100 | 1 101 | 1 101 | 2