I have a simple permission system with 3 tables: users
, permissions
and permission_user
. I would like to get all granted permissions with information who it has been granted to. The results should be ordered by:
- The number of permissions for user (his power), strongest first
- The date user has been created, oldest first
- The weight of permission (
weight
column), smallest first
Here's my query:
SELECT `users`.`email`,
`permissions`.`key`
FROM `users`
JOIN `permission_user` ON `permission_user`.`user_id` = `users`.`id`
JOIN `permissions` ON `permissions`.`id` = `permission_user`.`permission_id`
ORDER BY (
SELECT COUNT(*)
FROM `permission_user`
WHERE `user_id` = `users`.`id`
) DESC,
`users`.`created_at` ASC,
`permissions`.`weight` ASC;
It works fine, but I'm wondering if there is any way to do it without a subquery or counting total permissions granted. It's something that is present in the results set, I could just count unique user ID from that, but is that possible?