核心数据功能类似于WHERE ='(sql查询)'

时间:2012-03-02 12:48:00

标签: objective-c sql core-data nspredicate

如何运行sql查询CoreData类似于此:

SELECT COUNT(*) FROM headphones WHERE id IN (SELECT id FROM old_headphones);

我阅读了NSPredicate指南和NSExpression,但不明白如何做到这一点。

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT COUNT(distinct headphones.Id) 
FROM headphones 
    INNER JOIN old_headphones ON
        headphones.Id = old_headphones.Id

当耳机和old_headphones之间没有n-to_1关系时,您可以省略DISTINCT。

答案 1 :(得分:0)

/*First request*/
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription 
                               entityForName:@"headphones" inManagedObjectContext:yourContext];
[fetchRequest setEntity:entity];

NSError *error;
NSArray *fetchedObjects = [yourContext executeFetchRequest:fetchRequest error:&error];

/*2nd request*/
NSFetchRequest *fetchRequest2 = [[NSFetchRequest alloc] init];
NSEntityDescription *entity2 = [NSEntityDescription 
                               entityForName:@"old_headphones" inManagedObjectContext:yourContext];
[fetchRequest setEntity:entity2];

NSError *error;
NSArray *fetchedObjects = [yourContext executeFetchRequest:fetchRequest2 error:&error];

//use your 2 NSArray to find your headphones