利用SOQL 的Aggregate Functions (SUM,MAX,MIN...) 让代码更加的优雅,高效和稳定

本文通过对比两种不同的Salesforce查询方式,展示了如何利用AggregateFunctions进行数据聚合以提高查询效率。具体比较了未使用AggregateFunctions时的繁琐操作与使用后的简化流程。

1.没用Aggregate Functions的代码如下:

Set<Id> set_AccountIds = new Set<Id>();
map<Id,list<Datetime>> map_AccountId_LastModifiedDate = new map<Id,list<Datetime>>();
for(ObjectTerritory2Association OTTAobj: [SELECT ObjectId, LastModifiedDate FROM ObjectTerritory2Association]){
    if(map_AccountId_LastModifiedDate.get(OTTAobj.ObjectId) == null) {
        map_AccountId_LastModifiedDate.put(OTTAobj.ObjectId, new list<Datetime>());
    }
    map_AccountId_LastModifiedDate.get(OTTAobj.ObjectId).add(OTTAobj.LastModifiedDate);
}
for(Account account : [SELECT Id, Last_Batch_Job_Run_DateTime__c FROM Account WHERE Id IN :map_AccountId_LastModifiedDate.keyset()]){
    map_AccountId_LastModifiedDate.get(account.Id).sort();
    Datetime maxLastModifiedDate = map_AccountId_LastModifiedDate.get(account.Id).get(map_AccountId_LastModifiedDate.get(account.Id).size() -1);
    if(account.Last_Batch_Job_Run_DateTime__c == null){
        set_AccountIds.add(account.Id);
    }else if(account.Last_Batch_Job_Run_DateTime__c < maxLastModifiedDate){
        set_AccountIds.add(account.Id);
    }
}

 

2.使用Aggregate Functions的代码如下:

Set<Id> accountIds = new Set<Id>();
Map<Id,Datetime> accountDateMap = new map<Id,Datetime>();
AggregateResult[] groupedResults = [SELECT ObjectId, Max(LastModifiedDate) FROM ObjectTerritory2Association GROUP BY ObjectId];
for (AggregateResult ar : groupedResults)  {
    accountDateMap.put(String.valueOf(ar.get('ObjectId')), (Datetime)ar.get('expr0'));
}
for(Account account : [SELECT Id, Last_Batch_Job_Run_DateTime__c FROM Account WHERE Id IN :accountDateMap.keyset()]){
    if(account.Last_Batch_Job_Run_DateTime__c == null){
        accountIds.add(account.Id);
    }else if(account.Last_Batch_Job_Run_DateTime__c < accountDateMap.get(account.Id)){
        accountIds.add(account.Id);
    }
}

 

利用Aggregate Functions 重写的代码2,更加易于阅读和高效

想象一下 :例如ObjectTerritory2Association 里面有1W条数据,ObjectId 分类只有3千

转载于:https://my.oschina.net/oakgong/blog/1550408

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值