+ Start a Discussion
Patrick ConnerPatrick Conner 

Multiple Object Query with SOQL

I'm trying to create an SOQL Query for the controller of a custom VisualForce page. Is there any way to run a single SOQL query that can search fields in two different non-related objects? I'm aware that this can be done in SOSL, but there are specific reasons SOQL is required for this particular function (please no SOSL responses). 

Basically I'd like to combine the following (examples):

SELECT Name, Email, Phone FROM Contact WHERE Phone != null AND PhoneSearch1__c LIKE '%0149%' order by Name asc limit 75

SELECT Name, Email__c, Phone FROM Account WHERE Phone != null and PhoneSearch1__c LIKE '%0149%' order by Name asc limit 75

This might could be done by assigning the queries as variables? I'm not sure. Any help would be greatly appreciated! Thanks!
If Account and Contact object don't have related record then you can not do this by single query
If Account and contact have realtionship record then you can use inner query with semi joins.
Well I dont think there is a way you can do this using a single SOQL. You have to fire two different SOQL to obtain the records from unrelated objects
Bhawani SharmaBhawani Sharma
You can't.
But in terms of minimizing the duplicate code, you can use dynamic soql query. If you are sure that your fields are where clause criteria is going to be the same, you can have a variable for refering the object name. Make sure each query will count as separate.
James LoghryJames Loghry
You could potentially do this with a relational query, but only if, as Summer 14 said, you have a relationship between the two objects.  The query would be pretty expensive in terms of performance, however.  Furthermore, you would need to query on the Child object or Contacts in your case.  Anything else would return in errorneous results.

List<Contact> contacts =
        Phone != null
            (PhoneSearch1__c LIKE '%0149%' 
            Or Account.PhoneSearch1__c Like '%0149%' )
     Order By 
        Name asc 
     Limit 75];