3
  • Custom child object - Student
  • Custom parent object - College

I understand how to query all student records when a college name is given:

List<Student__c> a = [
    SELECT Id, Name FROM Student__c WHERE College_Name__r.Name = 'PEC College'
];

How can I query to get college info when a student name is given?

  • 3
    Get onto Trailhead ..developer.salesforce.com/trailhead/en/module/… – Mohith Shrivastava Mar 13 '16 at 17:50
  • Can't answer unless it gets reopened, but you can do an inner-join sub-select: SELECT Name FROM College__c WHERE Id IN (SELECT College__c FROM Student__c WHERE Name='Joe Schmo') – Adrian Larson Mar 14 '16 at 19:08
  • Adrian- It worked, I got the college name. But, the log displays the id as well? – SF99 Mar 14 '16 at 19:29
1

You can do an inner-join sub-select:

SELECT Name FROM College__c WHERE Id IN (
    SELECT College__c FROM Student__c WHERE Name='Joe Schmo'
)

Every query you ever run in Apex is going to also return the Id field. You cannot omit it from the results in this context.

2
  1. Query parent-to-child, which are almost always one-to-many. Specify these relationships using a subquery (enclosed in parentheses), where the initial member of the FROM clause in the subquery is related to the initial member of the outer query FROM clause. Note that for subqueries, you should specify the plural name of the object as that is the name of the relationship for each object.

    SELECT Name,
    (
     SELECT LastName
    FROM Contacts
    WHERE CreatedBy.Alias = 'x') 
    FROM Account WHERE Industry = 'media'
    
  2. Query child-to-parent relationships, which are often many-to-one. Specify these relationships directly in the SELECT, FROM, or WHERE clauses using the dot (.) operator.

    SELECT Id, Name, Account.Name
    FROM Contact 
    WHERE Account.Industry = 'media'
    

You can read more about different relationship queries from Salesforce https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships.htm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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