I've been trying to get a handle on this, but no luck, so it'd be great if someone can help me.
I've got 2 tables. Items and Item Flags.
Item
id name levelid containertypeid roomid userid timestamp
-- ---- ------- --------------- ------ ------ -----
1 Item 1 0 0 3 5 1365072108
2 Item 2 0 0 3 5 1365342108
3 Item 3 0 0 3 5 1389072108
4 Item 4 0 0 3 5 1365085108
5 Item 5 2 3 3 5 1365962108
6 Item 6 1 3 3 5 1365322108
Item_Flags
id itemid flagid userid timestamp
-- ---- ------- ------- ---------
1 1 1 5 1365072108
2 1 5 5 1365342108
3 1 2 5 1389072108
4 1 3 5 1365085108
5 2 4 5 1365762108
6 2 1 5 1365921087
7 2 3 5 1365252108
8 3 6 5 1365982108
9 3 7 5 1365312108
10 3 8 5 1365342108
The Goal
What I'm trying to do is get a list of all items, sorted by a descending timestamp. So, effectively, I want a list of items based on the latest timestamp from when we either updated the actual item or added a flag for the item. The application updates the timestamp each time a flag is added against a particular item or whenever the item name or level is updated. The problem is that I cannot run a GROUP BY if I want to get back the name, levelid, etc. fields because I have use them in an aggregate function, so the real value does not come back. If I don't group them, I obviously get multiple results for each item depending on how many flags it has. Here is my query:
SELECT
items.id,
items.name,
items.levelid,
items.containertypeid,
items.roomid,
items.userid
FROM
items
LEFT OUTER JOIN item_flags ON
items.id = flags.itemid
WHERE
items.levelid = 0 AND
items.containertypeid = 0 AND
items.room = 3 AND
items.userid = 5
GROUP BY
items.id
ORDER BY
items.timemodified DESC
item_flags.timemodified DESC
I can get this to work if I wrap all of my select fields except items.id in aggregate functions and remove the ORDER by altogether, but I need to use those fields when I get them back and I need them ordered! I'm not even sure at this point if the logic in the query makes sense because whilst I am saying that the flags.itemid is equal to items.id, there is a one to many relationship there.
I've had a look at SQL Query - Grouping with multiple tables, but there isn't an ORDER BY there and I can't figure out how to make it work!
Using PG SQL.
Thanks!
==================================
As it turns out, at the end of it all, the query had to work with MySQL too and the With obviously does not work. So we've come up with a different solution which I'm running tests on will post as soon as I have, in case it might be useful for someone else.