Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I have two Objects object1 & object2.

In object1 there is a field, field1 with Lookup to object2. Now what I need to do is query object2 fields based on the id of field1 How can I perform this query?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

UPDATE:

Let say you know the Id of Object1. So you can read the Field1__c from that Object1 - this will be Id of the Object2.

Id idOfObject2 = [ Select Field1__r.Id From Object1 Where Id = :someVar ].Field1__r.Id;

Now we reading Object2 fields:

Object2 obj2 = [ Select Field1__c, Field2__c From Object2 Where Id = :idOfObject2 ];

Or we can do the same simpler:

Object2 obj2 = [ Select Field1__c, Field2__c From Object2 
                 Where Id IN (Select Field1__c From Object1 Where Id = :someVar) ];

I think you can do it like this:

Select Id, Name From Object2 Where Id = :Object1.field1__c

You can read more about lookup relationships at the official doc site: Relationship Queries

share|improve this answer
    
I can't go with the second one because all my fields are in object2,so need to query object2....and for the first one getting error as Compile Error: Variable does not exist: object1__r.field1__c –  Eagerin Sf Dec 13 '12 at 8:02
    
What is your key? I mean - based on which id you are reading the data? –  mast0r Dec 13 '12 at 8:06
    
Thats Perfect...Thanks –  Eagerin Sf Dec 13 '12 at 8:27

You can also do this thriugh one single query -

[Select  Field2__r.Field2_field__c FROM Object1 obj where obj.id = :Object1ID];
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.