function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
FrankFFrankF 

Single Query to join Cmapaign and CampaignMember?

What I would like to do is get a list of Campaign Names for a given Lead.

 

I can do this via 2 soql queries - 

 

campaignids  = [select CampaignId from CampaignMember where LeadId='00Q7000000XXXXX]

 

and then 

 

campaignNames= [select Name from Campaign where Id in :campaignids]

 

is there a way to do this in one query?

 

I've tried select Name from Campaign where CampaignMembers__r.LeadId = '00Q7000000XXXXX'since I see that Campaign has a child relationship with CampaignMember but that doesn't seem to work.

 

Any help would be much appreciated.

 

Frank.

jkucerajkucera

Are you concerned about governor limits?  I believe nested queries only count as 1 soql query:

 

 

Id LeadId = '00Q7000000XXXXX'; List<String> CampaignNames=[SELECT Name FROM Campaign WHERE Id IN [SELECT CampaignID FROM CampaignMember WHERE LeadId =: leadId]];

 You might have to add ".Name" just after the "]]" (ie- "...leadId]].Name" to get this to work as a string list.

 

jkucerajkucera

<I deleted my bad syntax post & replaced with the below>

 

Here's my "revised" example.  Note you can only assign the query to an sObject CampaignMember:

 

 

List<CampaignMember> CampaignNames = [SELECT Campaign.Name FROM CampaignMember WHERE LeadID =:leadId]; for(CampaignMember cm: CampaignNames){ system.debug('Campaign Name: '+cm.Campaign.Name); }

 

Note the syntax to get the name is CampaignMember.Campaign.Name

 

The difference between this approach & my previous post is that this one will have duplicate Campaigns in there if you have more filter on more than 1 lead ID wherease my previous example will not have duplicate Campaigns (and their names) if 2 leads are in the same campaign.

 

Message Edited by jkucera on 02-19-2010 04:26 PM
werewolfwerewolf

Couple of typos in there, it should read:

 

List<String> CampaignNames=[SELECT Campaign.Name FROM CampaignMember WHERE LeadId=:leadId];