I am working on a project where users need to have permissions based on which department they are connected to.
So now I am trying to do a query that will show me users that have all necessary permissions based on the users department_id (users that do not have all necessary permissions shall not be displayed in the result).
I have been trying lot of different things (different type of JOINS, sub queries w/where in, exists and union distinct) without luck, this kind of query is next level for me and challenges my logical thinking.
Tables:
users
id
first_name
last_name
department_id
permissions
id
name
departments (relation to groups and categories based on department)
id
name
category_id
group_id
categories
id
name
groups
id
name
departments_permissions (permission requirement)
department_id
permission_id
categories_permissions (permission requirement)
category_id
permission_id
groups_permissions (permission requirement)
group_id
permission_id
users_permissions (users have permissions here)
user_id
permission_id
Department
- A department CAN (not required) have many permissions (departments_permissions).
- A department CAN (not required) have a category.
- A department CAN (not required) have a group.
Category
- A category CAN (not required) have many permissions (categories_permissions).
Group
- A group CAN (not required) have many permissions (groups_permissions).
Important side note
departments_permissions, categories_permissions and groups_permissions can contain one or more of the same permission_id's, therefore we have to select distinct values.
Example data
My latest query attempt:
SELECT
`users`.id,
`users`.first_name,
`users`.last_name,
`users`.department_id
FROM
`users`
INNER JOIN
`departments` ON `users`.department_id = `departments`.id
INNER JOIN
`users_permissions` ON `users`.id = `users_permissions`.user_id
INNER JOIN
(
SELECT permission_id FROM departments_permissions WHERE department_id = departments.id
UNION DISTINCT
SELECT permission_id FROM categories_permissions WHERE category_id = departments.group_id
UNION DISTINCT
SELECT permission_id FROM groups_permissions WHERE group_id = departments.group_id
) AS tblPermissionsRequired ON `users_permissions`.permission_id = `tblPermissionsRequired`.permission_id
GROUP BY
`users_permissions`.user_id;