I'm new to iOS development and I'm trying to understand how to use a subquery with NSPredicate so that I can limit rows to only the most recent entry for a particular user. See the table below. This all works with sqlite.
Here is a sample table and data that represents the problem well.
BEGIN TRANSACTION;
CREATE TABLE `user_orders` (
`timestamp` INTEGER,
`username` TEXT,
`items_ordered` TEXT
);
INSERT INTO `user_orders` (timestamp,username,items_ordered) VALUES (0,'joe','pencil');
INSERT INTO `user_orders` (timestamp,username,items_ordered) VALUES (1,'joe','coffee');
INSERT INTO `user_orders` (timestamp,username,items_ordered) VALUES (2,'joe','book, gum, coffee');
INSERT INTO `user_orders` (timestamp,username,items_ordered) VALUES (1,'sam','tea');
INSERT INTO `user_orders` (timestamp,username,items_ordered) VALUES (5,'sam','book');
COMMIT;
I need to translate this statement into a NSFetchRequest.
SELECT t1.* FROM user_orders AS t1
JOIN (SELECT username, MAX(timestamp) AS timestamp FROM user_orders GROUP BY username) AS t2
WHERE t1.username = t2.username AND t1.timestamp = t2.timestamp
Here is what should be returned.
timestamp, username, items
"2" "joe" "book, gum, coffee"
"5" "sam" "book"
I've dug into the documentation, but I'm struggling with finding examples. I'm not sure how to reference the outer table from the subquery.
Also, is there an easy way to test queries as you program inside XCode?