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

Answer by mike16889 for Conditional inner join

$
0
0

Based on Lennarts suggestion I have used a UNION to get the results I need:

SELECT u.uID, it.itID, u.user, it.itemTypeFROM users uINNER JOIN clientItemTypes cit ON cit.cID = u.CIDINNER JOIN userGroupItemTypes ugit ON ugit.ugID = u.ugIDINNER JOIN itemTypes it ON it.itID = ugit.itIDINNER JOIN (SELECT COUNT(ugit.ugID) AS total, uID FROM users u LEFT JOIN userGroupItemTypes ugit ON u.ugID = ugit.ugID GROUP BY uID) c ON c.uID = u.uIDWHERE c.total > 0GROUP BY uID, itIDUNIONSELECT 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.itIDINNER JOIN (SELECT COUNT(ugit.ugID) AS total, uID FROM users u LEFT JOIN userGroupItemTypes ugit ON u.ugID = ugit.ugID GROUP BY uID) c ON c.uID = u.uIDWHERE c.total = 0GROUP BY uID, itID

dbfiddle

Basically running the same queries twice, one requiring a userGroup to have itemTypes, the other requiring the userGroup NOT to have itemTypes, then using the union to combine the results.

I'm not sure if this is the most efficient way of doing it but it will have to do unless I can find another way of doing it.


Alternative Solution (thanks to Lennart):

Using EXISTS and NOT EXISTS

SELECT u.uID, it.itID, u.user, it.itemTypeFROM users uINNER JOIN clientItemTypes cit ON cit.cID = u.CIDINNER JOIN userGroupItemTypes ugit ON ugit.ugID = u.ugIDINNER JOIN itemTypes it ON it.itID = ugit.itIDWHERE EXISTS (    SELECT 1 FROM userGroupItemTypes ugit    WHERE u.ugID = ugit.ugID)GROUP BY uID, itIDUNIONSELECT 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.itIDWHERE NOT EXISTS (    SELECT 1 FROM userGroupItemTypes ugit    WHERE u.ugID = ugit.ugID)GROUP BY uID, itID

dbfiddle


Viewing all articles
Browse latest Browse all 2

Trending Articles