Apex Get Account Record Ids where Contact First Name is in LIST ( using AND Condition )

Viewed 571

In Salesforce I would like to retrieve AccountIds where its related Contact FirstName must have values in list of String. List of string is {'Test','User'}. I would need to find all Accounts where Contact first Name has both Test and User as related Contacts,

I am trying as below but the below query will show accounts where even 1 value matches as Contact First Name.

List<String> names = new List<String>{'Test','User'}; List<Account> accountList =         [ Select Id from Account Where Id IN         (Select AccountId FROM Contacts where FirstName LIKE :names)];

Please help

1 Answers
SELECT Id, Name
FROM Account
WHERE Id IN (SELECT AccountId FROM Contact WHERE LastName = 'Test')
AND Id IN (SELECT AccountId FROM Contact WHERE LastName = 'User')

But it'll work only 2 times, you can't write 3rd "IN" like that (see here).

If you need a more generic solution that can take lists of any size you'd have to run "my" queries in loop, 2 names at a time, save results to some Set<Id> or Map, play with functions like myset.retainAll(idsFromCurrentLoopQuery)... Of course query in a loop is bit evil too.

Related