SQL INNER JOIN CASE SPECIFIC

时间:2013-07-21 09:50:08

标签: sql sql-server sql-server-2008 sql-server-2005

以下是我的数据库表结构

ApplicationModule - Id,Key,Name

ApplicationFeature - Id,ModuleId,Key,Name

每个功能都与Module一起映射。此外,我只需要为租户分配一些功能。

TenantXFeature - TenantId,FeatureId

此外,当我创建角色时,我会映射从Tenant Specific(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总是显示NULL,即使我在RoleXFeature中有映射。

请建议/帮我解决此问题。

1 个答案:

答案 0 :(得分:0)

可能同时没有与id = 1的角色和id = 1的租户相关的功能

与角色ID = 1或租户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))

与角色ID = 1和租户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