Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find list of GROUPIDs that have ZERO AccountIDs on another table

Looking for SQL that returns a list of GROUPIDs (from the ACCOUNT_GROUP) table that have no ACCOUNTS that are found on the ACCOUNT_LIST table.

ACCOUNT_GROUP (table)

GROUPID ACCOUNT
GROUP1 111111
GROUP1 222222
GROUP1 333333
GROUP2 222222
GROUP3 333333
GROUP4 444444

ACCOUNT_LIST (table)

ACCOUNT
111111
222222
444444

The result should return only GROUP3 since this is the only GROUPID that does not have at least one account in the ACCOUNT_LIST table.

I have tried a few WHERE NOT EXISTS, not getting the correct results

This returns GROUPIDs that have an Account that is not in the ACCOUNT_LIST table even if it has some that do exist (which is not what I need)

SELECT DISTINCT GROUPID
FROM ACCOUNT_GROUP T1
WHERE NOT EXISTS (
    SELECT 1
    FROM ACCOUNT_LIST T3
    WHERE T1.ACCOUNT = T3.ACCOUNT
)
like image 817
Don Neary Avatar asked Sep 20 '25 12:09

Don Neary


1 Answers

A simple left anti-join with aggregation should work here:

SELECT AG.GROUPID
FROM ACCOUNT_GROUP AG
LEFT JOIN ACCOUNT_LIST AL
    ON AL.ACCOUNT = AG.ACCOUNT
GROUP BY AG.GROUPID
HAVING COUNT(AL.ACCOUNT) = 0;
like image 103
Tim Biegeleisen Avatar answered Sep 23 '25 04:09

Tim Biegeleisen