简体   繁体   English

标记一个表中的行,其中值存在于连接表中?

[英]Mark rows from one table where value exists in join table?

For my query, I have two tables, as defined below:对于我的查询,我有两个表,定义如下:

permissions table:权限表:

| permission_id | permission_description |
|---------------|------------------------|
|             1 | Create User            |
|             2 | Edit User              |
|             3 | Delete User            |

users_permissions table: users_permissions表:

| permission_id | user_id |
|---------------|---------|
|             1 |       1 |
|             1 |       2 |
|             3 |       2 |
|             3 |       5 |
|             1 |       3 |
|             3 |       1 |

Now, I need to retrieve a list of all permissions in the permissions table, with a column to indicate if the user with user_id of 1 exists for each permission in the users_permissions table.现在,我需要检索permissions表中所有权限的列表,其中有一列指示对于users_permissions表中的每个权限是否存在user_id1的用户。

So, my desired output for the query would be:所以,我想要的查询输出是:

| permission_id | permission_description | has_permission |
|---------------|------------------------|----------------|
|             1 | Create User            | TRUE           |
|             2 | Edit User              | FALSE          |
|             3 | Delete User            | TRUE           |

So far, I have tried the following query, but it returns entries for all permissions and all user_id values:到目前为止,我已经尝试了以下查询,但它返回所有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;

How do I limit that to just one entry per permission ?如何将每个permission限制为一个条目?


For clarity, the end goal is to get a list of available permissions and mark the ones the user already has.为清楚起见,最终目标是获取可用权限列表并标记用户已经拥有的权限。

If you only want to know the answer for one user then an exists subquery will do the job - no need for a join.如果您只想知道一个用户的答案,那么exists subquery就可以完成这项工作——不需要加入。

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

PS - I wouldn't recommend having a table called permissions as its a reserved word in SQL Server. PS - 我不建议将名为permissions的表作为 SQL Server 中的保留字。

Use LEFT JOIN instead of INNER JOIN and check if it is null使用LEFT JOIN而不是INNER JOIN并检查if it is null

select permissions.permission_id,
       permission_description,
       case when user_id is null then 'FALSE' else 'TRUE' END as has_permission
FROM permissions
LEFT JOIN users_permissions 
  ON permission.permission_id = users_permissions.permissions_id and user_id = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM