Retrieve group members from a group which are only other groups

governorlimitssoql

SELECT Id, Name, DeveloperName, Type, RelatedId,
        (
            SELECT UserOrGroupId
            FROM GroupMembers
            WHERE UserOrGroupId IN (
                SELECT Id
                FROM Group
                WHERE UserOrGroupId IN (SELECT Id FROM Group)
            )
        )
    FROM Group

I was using the above quite happily on the API however we need to move this over to APEX and that doesn't support nesting semi joins how else can I restrict GroupMembers to only return group members related to this group that are groups and not users. I cannot filter after the fact as there are too many users, and I will hit my governor limits.

EDIT:
I have tried going from the membership out using the below but the issue is the last level of groups don't have group memberships therefore don't show up. As I don't want to query every single group and group membership this isn't really practical.

SELECT Id, Group.Id, Group.Name, Group.DeveloperName,
    Group.OwnerId, Group.Type, Group.RelatedId, Group.Email,
    Group.DoesSendEmailToMembers, Group.DoesIncludeBosses, Group.QueueRoutingConfigId,
    UserOrGroupId
FROM GroupMember
WHERE UserOrGroupId IN (
    SELECT Id
    FROM Group
)

Best Answer

Unless I'm missing something, couldn't it just be:

SELECT Id, Name, DeveloperName, Type, RelatedId,
    (
        SELECT UserOrGroupId
        FROM GroupMembers
        WHERE UserOrGroupId IN ( SELECT Id FROM Group WHERE Type = 'Regular' )
    )
FROM Group