基于将一个视图中的值列表与另一个视图中的列表进行比较,返回 table
Returning table based on comparing list of values in one View to a list in another
我有两个 SQL 视图公开与实体/分类配对相关的数据,另一个公开用户分类配对。
为了让用户有权访问实体,用户必须拥有分配给该实体的所有类别。所以:
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 可以访问实体 ID 1 和 2
我希望能够 return 像这样 table 中的数据,本质上是一个完整的权利列表和有权访问它们的用户:
UserID EntityID
100 1
101 1
101 2
实现此目标的最佳和最有效的方法是什么。我正在使用 SQL 服务器 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
我有两个 SQL 视图公开与实体/分类配对相关的数据,另一个公开用户分类配对。
为了让用户有权访问实体,用户必须拥有分配给该实体的所有类别。所以:
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 可以访问实体 ID 1 和 2
我希望能够 return 像这样 table 中的数据,本质上是一个完整的权利列表和有权访问它们的用户:
UserID EntityID
100 1
101 1
101 2
实现此目标的最佳和最有效的方法是什么。我正在使用 SQL 服务器 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