Quantcast
Channel: Conditional inner join - Database Administrators Stack Exchange
Viewing all articles
Browse latest Browse all 2

Conditional inner join

0
0

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 3

clients

cID     client1       Client 1

userGroups

ugID    userGroup1       Group 12       Group 2

users

uID     user     cID     ugID1       Fred     1       12       Sam      1       2

clientItemTypes

cID     itID1       11       21       3

userGroupItemTypes

ugID    itID2       12       2

Resaults 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 3

Basically 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


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles



Latest Images