如何将此SQL查询转换为NSFetchRequest

时间:2014-11-07 20:30:11

标签: ios sql core-data nspredicate nsfetchrequest

如何将此SQL查询转换为NSFetchRequest:

select max(ZSENTAT), * from ZMESSAGE where ZISINCOMING == 1 group by ZROOTMESSAGEID;

这是我走了多远:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"isIncoming == %@ AND sentAt == @max.sentAt", [NSNumber numberWithBool:YES]];
NSFetchRequest *request = _fetchedResultsController.fetchRequest;
request.predicate = predicate;
request.propertiesToGroupBy = @[ @"rootMessageId" ];

这会导致异常:'NSInvalidArgumentException',原因:'具有GROUP BY组件的查询中的SELECT子句只能包含GROUP BY或聚合函数中指定的属性

由于 克里斯

1 个答案:

答案 0 :(得分:2)

出现错误是因为您需要将提取限制为"组中的那些属性。和任何集合功能。在您的情况下,您需要将其限制为rootMessageIdmax(sentAt)。为此,您必须指定NSFetchRequest' s propertiesToFetch请注意,如果您这样做,那么您必须将其resultType指定为NSDictionaryResultType,这将限制您使用NSFetchedResultsController

如果你想要实现你的获取:指定rootMessageId很容易,指定max(sentAt)需要更多的工作。您必须创建NSExpressionNSExpressionDescription。看看这些Apple文档,但以下内容可以帮助您入门:

NSExpression *maxExpression = [NSExpression expressionWithFormat:@"max:(sentAt)"];
NSExpressionDescription *maxDesc = [[NSExpressionDescription alloc] init];
maxDesc.name = @"maxSentAt";
maxDesc.expression = maxExpression;
maxDesc.expressionResultType = NSDateAttributeType; // I assume sentAt is a NSDate
request.propertiesToFetch = @[@"rootMessageId", maxDesc];
request.propertiesToGroupBy = @[@"rootMessageId"];
request.resultType = NSDictionaryResultType;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"isIncoming == %@",[NSNumber numberWithBool:YES]];
request.predicate = predicate;
NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&error];
etc

结果数组将包含带有两个键的字典:" rootMessageId"和" maxSentAt"。