Imagine the following table:
Id type created flag
-----------------------------------------------------
1 1 2015-12-11 12:00:00 0
2 1 2015-12-11 12:10:00 0
3 2 2015-12-11 12:00:00 0
4 2 2015-12-11 12:10:00 0
5 3 2015-12-11 12:00:00 0
6 3 2015-12-11 12:10:00 0
--------------------------------------------------------
I want to write a query that will set the flag to 1 (TRUE) for each row with the most recent created date for each type grouping. Ex, the result should be:
Id type created flag
-----------------------------------------------------
1 1 2015-12-11 12:00:00 0
2 1 2015-12-11 12:10:00 1
3 2 2015-12-11 12:00:00 0
4 2 2015-12-11 12:10:00 1
5 3 2015-12-11 12:00:00 0
6 3 2015-12-11 12:10:00 1
--------------------------------------------------------
I know that
UPDATE table
SET flag = TRUE
ORDER BY created DESC
LIMIT 1;
will set the flag for the most recent date, but I'm stuck on how to apply this for each group.
I've also tried:
UPDATE table t
INNER JOIN
(SELECT id, flag, MAX(created) as maxdate
FROM table
GROUP BY type) as m
SET flag = TRUE
WHERE m.id = t.id AND t.created = m.maxdate;