'MySQL Subquery managing different cases
I'm having a problem writing a complex query.
This is the database structure:
collections
__________________________
| id | title |
--------------------------
| 123 | With Group |
--------------------------
| 321 | No groups |
-------------------------
collection_categories
___________________________________
| id | id_collection | id_category|
-----------------------------------
| 1 | 123 | 32 |
-----------------------------------
groups_categories
_______________________________
| id | id_category | id_group |
-------------------------------
| 2 | 32 | 11 |
-------------------------------
users_groups
___________________________
| id | id_user | id_group |
---------------------------
| 1 | 345 | 11 |
---------------------------
| 2 | 674 | 12 |
---------------------------
The final result is that: For the collections with id 123 -> check all tables to understand if user can access to it, basically in this example id_user 346 can access to collection with id 123, id_user 674 can't access to it. Both of them can access to collection with id 321.
There is a way how can I manage this cases both from MySQL without do some additional check in the backend code? Because in my tests, when I do the check, in case of id_user 674 I can't get results. (with a Join query, users_groups does not have elements that match with groups_categories).
Thanks guys, I'll add here more informations as I do more tries.
EDIT 1: Rows can be missing inside the tables and there is no need to check groups_categories and collection_categories, it's enough to check the absence of one or more rows inside collection_categories with the id_collection, I can just show up collections. Example: SELECT * FROM collections WHERE (id=123 OR id=321) AND other things to check here In this case depended from users I'll get different outputs. I can get both or one of two.
ID_USER 674 can't access to collection with ID 123 because that collection has a category that is inside a group that not contains user 674.
EDIT 2: I was trying to add a NOT EXISTS AND EXISTS concatenated with an OR operator into the query:
NOT EXISTS -> to check if that id_collection is not present inside the groups_categories
EXISTS -> to check if id_collection is present inside the groups_categories and if the id_user is inside users_groups where users_group.id_group = groups_categories.id_group
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
