2

下面是我的数据库表结构

ApplicationModule- ID、密钥、名称

ApplicationFeature- ID、ModuleId、密钥、名称

每个功能都映射到模块。此外,我只需要为租户分配一些功能。

TenantXFeature- 租户 ID、功能 ID

此外,当我创建角色时,我映射了从租户特定(TenantXFeature)中挑选的一些特征

RoleXFeature- RoleId,FeatureId

现在我需要一个查询来加载所有租户特定的功能以及选择(Y/N),如果 RoleXFeature 具有该功能的条目。

SELECT AM.[Key] AS ModuleKey
      ,AM.Name AS ModuleName
      ,AF.[Key] AS FeatureKey
      ,AF.Name FeatureName
      ,RF.FeatureId
      ,CASE WHEN RF.FeatureId IS NULL THEN 0 ELSE 1 END AS Selected
  FROM TenantXFeature TF
  INNER JOIN ApplicationFeature AF
    ON TF.FeatureId = AF.Id
  INNER JOIN ApplicationModule AM
    ON AF.ModuleId = AM.Id 
  LEFT JOIN RoleXFeature RF
    ON RF.FeatureId = AF.Id AND RF.RoleIid = 1
  WHERE TF.TenantId = 1

RF.FeatureId即使我在 RoleXFeature 中有映射,这里总是显示 NULL。

请建议/帮助我解决这个问题。

4

1 回答 1

0

Probably there are no features related at the same time to a role with id=1 and to tenant with id=1

Features not related to role id=1 or to tenant id=1:

SELECT *
FROM ApplicationFeature f
WHERE (NOT EXISTS(SELECT 1 FROM TenantXFeature WHERE FeatureId = f.Id AND TenantId=1)
OR NOT EXISTS(SELECT 1 FROM RoleXFeature WHERE FeatureId = f.Id AND RoleId=1))

Features related both to role id=1 and tenant id=1:

SELECT *
FROM ApplicationFeature f
WHERE EXISTS(SELECT 1 FROM TenantXFeature WHERE FeatureId = f.Id AND TenantId=1)
AND EXISTS(SELECT 1 FROM RoleXFeature WHERE FeatureId = f.Id AND RoleId=1)

Playground on SQLFiddle

于 2013-07-21T10:51:26.070 回答