简体   繁体   中英

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:

| 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.

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:

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 ?


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.

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.

Use LEFT JOIN instead of INNER JOIN and check 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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