0

I have two queries as follows: Is there a way to JOIN them in one query using the Question__r.Id?

(I know SOQL doesn't have JOINs, but maybe an alternative solution?)

List<Answer__c> l= [SELECT Answer__C,  
                   Question__r.Id, Question__r.Name 
                   FROM Answer__c WHERE Application__c = :appID];

List<Question_Category__c> q = [SELECT Order__c
                      Question__r.Id, Question__r.Name
                      FROM Question_Category__c WHERE Category__c = :catID];

I could make the above 2 queries and add them to a single map as the outcome, but I wanted to see if there were any other elegant solutions.

Adding to the above, is there a way to add the results of a query to a map and specify Question__r.Id as the key?

1
  • List<Question__c> ... FROM Question_Category__c won't compile. Please review your question and edit.
    – sfdcfox
    Commented May 12, 2020 at 0:58

1 Answer 1

2

You can write this as a single query on the parent object, apparently Question__c, with two parent-child subqueries. If would presumably look something like this, although your question doesn't contain all the schema details needed to make sure this is accurate:

SELECT Id, Name, 
       (SELECT Answer__c FROM Answers__r), 
       (SELECT Order__c FROM Question_Categories__r)
FROM Question
WHERE ...

You'd need to verify the child relationship names Answers__r and Question_Categories__r.

You can also include WHERE clauses on the subqueries to filter the child objects returned, if desired. I've omitted them here because it's not completely clear how you're intending to filter this related information if approaching through the parent object.

Note that as written your second query will not compile; you're querying Question_Category__c and assigning to a List<Question__c>.

1
  • 1
    ya beat me to it. I would like to add that there are several pieces of documentation that should help here. The Semi Joins and Anti Joins section of "Comparison Operators", and the "Using Relationship Queries" and "Understanding Query Results" parts of Relationship Queries
    – Derek F
    Commented May 12, 2020 at 1:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .