views:

21

answers:

1

What's the most efficient way to perform this query on a CoreData table? To use the standard employees database model -- I want DISTINCT department ID's for all departments that contain employees with job-description "chef." As it happens, there is only a single table (Employees) relevant here -- I don't actually have a departments table, just department ID's that are repeated.

+1  A: 

Given the schema you describe, I would execute a fetch with a predicate (format string) like @"jobDescription LIKE 'chef'" and then use key-value coding to get the unique values from the resulting array:

[result valueForKeyPath:@"@distinctUnionOfValues.departmentID"];

or create a set:

NSSet *deparmentIDs = [NSSet setWithArray:[result valueForKey:@"departmentID"]];

Depending on the size of the problem (how many employees), doing the final step in-memory may prove prohibitive. At this point, you'll have to create a Department entity and do the work to make sure you connect appropriate employees to each department. Then you can do a fetch of Departments with a predicate (format string) like @"ANY employees.jobDescription LIKE 'chef'" to get the departments with chef employees.

Barry Wark
Thanks! The second of these suggested solutions worked for me, but I decided to refactor to avoid expensive operations like this.
ed94133