简体   繁体   中英

How can I use the result of an inner join query in a left join query, in one query

I am using this query to get the user data from their session by session id

SELECT authorized_users.* 
  FROM sessions 
  JOIN authorized_users 
    ON authorized_users.user_id = sessions.user 
 WHERE sessions.id = 'SESSION_ID_HERE';

I am then using this query to get the user's permissions (bitwise) by comparing the permissions integer they have to a table full of all possible permissions

SELECT user_permissions.permission_name 
  FROM authorized_users 
  LEFT 
  JOIN user_permissions 
    ON authorized_users.permissions & user_permissions.bits 
 WHERE authorized_users.user_id = 'USER_ID_HERE' 
   AND user_permissions.app = 'global'

App name is global in this example however can be a range of different apps, permissions for all apps are stored in the same table with bits and permission name, bits can have duplicates therefore app name is used to differentiate which app permissions are needed.

How can I do this using one query?

My goal is to fetch the names of the permissions that the users have from their session id

Here are my tables:

sessions :

会话表

authorized_users :

授权用户表

user_permissions :

用户权限表

Your second query should look like:

SELECT up.permission_name 
FROM authorized_users au LEFT JOIN
     user_permissions up
     ON up.app = 'global' AND
        au.permissions & up.bits 
WHERE au.user_id = 'USER_ID_HERE' ;

The important part is moving the 'global' comparison to the ON clause. Proper use of table aliases is just a recommendation.

Then to get a particular session: SELECT up.permission_name FROM authorized_users au JOIN sessions s ON au.user_id = s.user LEFT JOIN user_permissions up ON up.app = 'global' AND au.permissions & up.bits WHERE s.id = 'SESSION_ID_HERE';

It is not clear why you need a LEFT JOIN . You might want to do this with just INNER JOIN s -- no rows would be returned if no permissions meet the conditions.

You can use a JOIN operation to put these two queries into one.

SELECT authorized_users.user_id, 
       user_permissions.permission_name 
  FROM sessions
  JOIN authorized_users 
             ON authorized_users.user_id = sessions.user
  LEFT JOIN user_permissions 
             ON authorized_users.permissions & user_permissions.bits 
            AND user_permissions.app = 'global'
 WHERE sessions.id = 'SESSION_ID_HERE';

If I understand your data correctly, this should get you a list of user ids and permission names for all users in the SESSION_ID_HERE session.

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