如何通过SOQL查询无关联地址或无默认地址的账户?
解决方法
可以实现,以下是两种可行的SOQL查询写法,都能筛选出无关联ContactPointAddress或者关联的ContactPointAddress中没有IsDefault=true记录的Account:
方法一:使用NOT IN子查询
SELECT Id, Name, (SELECT ContactPointAddress.Id, ContactPointAddress.IsDefault FROM ContactPointAddresses) FROM Account WHERE Id NOT IN ( SELECT AccountId FROM ContactPointAddress WHERE IsDefault = true )
原理:先查出所有关联了默认地址(IsDefault=true)的Account ID,然后取不在这个集合里的Account——自然包含了没有任何地址的Account,以及有地址但全是非默认的Account。
方法二:使用左外连接+分组统计
SELECT Id, Name, (SELECT ContactPointAddress.Id, ContactPointAddress.IsDefault FROM ContactPointAddresses) FROM Account a LEFT OUTER JOIN ContactPointAddress cpa ON a.Id = cpa.AccountId GROUP BY a.Id, a.Name HAVING COUNT(CASE WHEN cpa.IsDefault = true THEN 1 END) = 0
原理:通过左外连接保留所有Account,分组后统计每个Account下默认地址的数量。如果数量为0,说明要么没有关联地址,要么关联的地址里没有默认的。
内容的提问来源于stack exchange,提问作者I am not Fat
相关产品推荐
相关产品推荐

