[SalesForce] Inner SOQL child to parent query

I have written the below parent to child inner query which works :

        List<master__c> masterObj = new List<master__c>([Select id, (Select ID FROM detail__r) FROM Master__c]);

Which works fine. Similarly I am writing the child to parent inner query :

        List<master__c> masterObj = new List<master__c>([select id, (select id from master__c) from detail__c]);

        system.debug(masterObj);

it is giving error
** Line: 1, Column: 49
Didn't understand relationship 'master__c' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names.

Could you please help in identifying what is wrong with the query.

Thanks.

Best Answer

For parent field references the extra "select" keyword is not used:

List<detail__c> detailObj = [select id, master__r.Id from detail__c];

See the examples in the Using Relationship Queries documentation.

It is also not necessary to wrap the query results in a list; the query results are already a list of the correct type.

Related Topic