[SalesForce] Get all contacts and leads from campaign members

I can't think how to write a query to return all the contacts and all the leads (IDs, Names, and Phones) from CampaignMember.

I've never used much else rather than the standard [SELECT field FROM object WHERE criteria] format so I don't really know where to start.

At the start of the function I have the Id of the campaign, and two empty lists of Contact and Lead, which I'd like to populate. Can anyone help?

Best Answer

You should be able to do something like:

List<Contact> contacts = [
    SELECT 
        Id, Name, Phone 
    FROM 
        Contact 
    WHERE 
        Id IN (
            SELECT 
                ContactId 
            FROM 
                CampaignMember 
            WHERE 
                CampaignId = :campaignId AND ContactId != null
        )
];

List<Lead> leads = [
     SELECT 
         Id, Name, Phone 
     FROM 
         Lead 
     WHERE 
         Id IN (
             SELECT 
                 LeadId 
             FROM 
                 CampaignMember 
             WHERE 
                 CampaignId = :campaignId 
                 AND LeadId != null
         )
 ];