gpt4 book ai didi

ios - 如何将此 SQL 查询转换为 NSFetchRequest

转载 作者:行者123 更新时间:2023-11-29 10:36:25 25 4
gpt4 key购买 nike

如何将此 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 或聚合函数中命名的属性

谢谢克里斯

最佳答案

出现此错误是因为您需要将提取限制为仅“分组依据”中的那些属性和任何聚合函数。在您的情况下,您需要将其限制为 rootMessageIdmax(sentAt)。为此,您必须指定 NSFetchRequestpropertiesToFetch请注意,如果您这样做,则必须将其 resultType 指定为 NSDictionaryResultType,这将限制您使用 的更改跟踪(即委托(delegate)方法) >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”。

关于ios - 如何将此 SQL 查询转换为 NSFetchRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26809587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com