对于我的查询,我有两个表,如下所示:
权限表:
| permission_id | permission_description |
|---------------|------------------------|
| 1 | Create User |
| 2 | Edit User |
| 3 | Delete User |
users_permissions 表:
| permission_id | user_id |
|---------------|---------|
| 1 | 1 |
| 1 | 2 |
| 3 | 2 |
| 3 | 5 |
| 1 | 3 |
| 3 | 1 |
现在,我需要在permissions
表中检索所有全部权限的列表,并在其中显示一列,以表明是否拥有user_id
的用户1
users_permissions
表中的每个权限都存在。
因此,我的查询期望输出为:
| permission_id | permission_description | has_permission |
|---------------|------------------------|----------------|
| 1 | Create User | TRUE |
| 2 | Edit User | FALSE |
| 3 | Delete User | TRUE |
到目前为止,我已经尝试了以下查询,但是它返回所有permissions
和所有user_id
值的条目:
SELECT permissions.permission_id,
permission_description,
CASE WHEN user_id = 1 THEN 'TRUE' ELSE 'FALSE' END AS has_permission
FROM permissions
INNER JOIN users_permissions ON permission.permission_id = users_permissions.permissions_id;
如何将其限制为每个permission
仅一个条目?
为清楚起见,最终目标是获取可用权限列表并标记用户已经拥有的权限。
答案 0 :(得分:1)
如果您只想知道一位用户的答案,那么{
"compilerOptions": {...}
"include": [
"./",
"../your-library/**/*",
]
}
即可完成工作-无需加入。
exists subquery
PS-我不建议在SQL Server中使用名为SELECT P.permission_id
, P.permission_description
, CASE WHEN exists (select 1 from users_permissions UP where UP.permission_id = P.permission_id and UP.user_id = 1) THEN 'TRUE' ELSE 'FALSE' END AS has_permission
FROM [permissions] P
的表作为保留字。
答案 1 :(得分:0)
使用permissions
代替LEFT JOIN
并选中INNER JOIN
if it is null