I read a while back this excellent answer by @Bill Karwin:
https://stackoverflow.com/a/1313293/317889
This pretty much answers the question however, I have recently had to update my query to filter on the joined tables status.
I have written two queries below, similar to the queries in the post above. The first query which is the slow one works with the joined tables status filtering:
SELECT m.*, t1.* FROM mood m
LEFT JOIN temper t ON ( m._id = t.mood_id )
WHERE grantee_username = "username"
AND m.status_id != 1 // NOT INTERESTED IN THIS FILTER
AND t.status_id != 1 // FILTERING
GROUP BY m._id;
With the second query I have no idea how to add the filtering to get it to work as above:
SELECT m.*, t1.* FROM mood m
LEFT JOIN temper t1 ON ( m._id = t1.mood_id )
LEFT JOIN temper t2 ON ( t1.mood_id = t2.mood_id AND t1._id < t2._id )
WHERE t2._id IS NULL
AND m.grantee_username = "username"
AND m.status_id != 1; // NOT INTERESTED IN THIS FILTER
The first query works perfectly but is deemed to be slower than the second query.
The second query works at brining back all mood records with their relating last temper record however that last temper record may have a status of 1 which I don’t want.
Any insight would be of interest. I could always just go with the first query but for the sake of performance I would like to figure out how to add the t.status_id filtering to the second query if possible.
Ok, works out that it wasn’t too dificult after all:
The filter (status_id) needs to be added to each JOIN.