I need to get allowed itemTypes for a user based on 2 different tables in a conditional way. If the users userGroup has any entries in the userGroupItemTypes table it should only show items that are in common between userGroupItemTypes AND clientItemTypes but if no entries exist in userGroupItemTypes for that users userGroup, then it should just get all the ones from clientItemTypes
itemTypes
itID itemType1 Item 12 Item 23 Item 3clients
cID client1 Client 1userGroups
ugID userGroup1 Group 12 Group 2users
uID user cID ugID1 Fred 1 12 Sam 1 2clientItemTypes
cID itID1 11 21 3userGroupItemTypes
ugID itID2 12 2Resaults should be:
uID itID user itemType1 1 Fred Item 11 2 Fred Item 22 1 Sam Item 12 2 Sam Item 22 3 Sam Item 3Basically i think the query should function like follows:
SELECT u.uID, it.itID, u.user, it.itemTypeFROM users uINNER JOIN clientItemTypes cit ON cit.cID = u.CIDINNER JOIN itemTypes it ON it.itID = cit.itIDIF((SELECT COUNT(*) FROM userGroupItemTypes GROUP BY uID) > 0, INNER JOIN userGroupItemTypes ugit ON ugit.ugID = u.ugID, DO NOTHING)But I do not know how to actually achieve this. Any help would be greatly appreciated
EDIT:Here is a dbfiddle