通过添加新列值来连接两个表

时间:2017-08-10 14:06:13

标签: sql sql-server

我有两张表,比如

-----Permission Table-------|----RolePermission Table------
PermissionId    MenuName    | RoleId PemissionID
1                Home       |    1       1  
2                Incoming   |    2       1
3                Sent       |    1       3

我的查询就像这样

Select Permission.PermissionId, Permission.MenuName, RolePermission.RoleId,
case 
when 
Permission.PermissionId=RolePermission.PermissionId and RolePermission.RoleId=2 then 1
else 0 
end as IsAssignedRole
from Permission , RolePermission 

我想要这样的输出

PermissionId    MenuName    RoleId  IsAssignedRole
1               Home           2         1
2               Incoming       2         0
3               Sent           2         0

基本上我想获取绑定到我的复选框的所有权限menuname并检查权限ID是否已分配给角色,因此我可以设置选中相同的复选框。如果我传递null,它应该返回

PermissionId    MenuName    RoleId  IsAssignedRole
1               Home          Null       0
2               Incoming      Null       0
3               Sent          Null       0

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

使用left join。我认为这样做你想要的:

Select p.PermissionId, p.MenuName, rp.RoleId,
       (case when rp.PermissionId is not null then 1 else 0 end) as IsAssignedRole
from Permission p left join
     RolePermission rp
     on rp.PermissionId = p.PermissionId and rp.RoleId = 2 ;