I am trying to get the records of Contacts Whose phone equal to Account.phone.
Query:
select Account.name, name from contact where phone=Account.phone
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
Sign up to join this communityI am trying to get the records of Contacts Whose phone equal to Account.phone.
Query:
select Account.name, name from contact where phone=Account.phone
We cannot do a direct field to field comparison in a SOQL
.
As a workaround you can add a formula field(say AccountPhoneMatch__c
) on Contact object like,
IF(Phone = Account.Phone, 'true', 'false')
Then, query the Contact object
using this formula field, like this:
Select Account.name, name from Contact WHERE AccountPhoneMatch__c = true
See here for a similar article on this.
List<Account> accList= [select Id, Phone from Account];
List<string> accPhones = new List<String>();
for(Account acc : accList){
accPhones.add(acc.phone);
}
List<contact> contList= [select Account.name, name from contact where phone In :accPhones];
First of all, we need to find all the contacts corresponding to Account and then for each of the contact we need to check whether their phone is same as that of the Account's Phone.
List<Account> accList = new List<Account>();
Map<Id, Contact> conMap = new Map<Id, Contact>();
acclist = [Select Id, name, Phone, (Select ID, Name, Phone from Contacts) from Account];
for(Account a : accList){
List<Contact> conList = a.Contacts;
for(Contact c: conList){
if(c.Phone == a.Phone){
conMap.put(c.AccountId, c);
System.debug(conMap);
}
}
}