[SalesForce] Query all contacts in account related to opportunity

I am trying to pull a list of all contacts in accounts with certain opportunities. My initial query looks like this:

Select Id, Name , Account.id
From Opportunity 
WHERE RecordType.Name IN ('1A,'1B')

This identifies a few hundred opportunities, now what I can't figure out is how to relate this back to the associated Account to list all of the contacts in those Accounts. There should be a relation that would allow me to do this.

Best Answer

SOQL query will be like this, you need to join based on AccountId, which is known as Left Inner join query

SELECT Id, Name FROM Contact 
WHERE AccountId IN 
    (SELECT AccountId 
            FROM Opportunity 
            WHERE RecordType.Name IN ('1A','1B'))

For more information, refer A Deeper look at SOQL and Relationship Queries on Force.com

Related Topic