更新具有最大日期PER组的列的标志

时间:2015-12-11 23:58:55

标签: mysql

想象一下下表:

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
--------------------------------------------------------

我想编写一个查询,将每个行的标志设置为1(TRUE),并为每个类型分组创建最新的日期。例如,结果应该是:

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
--------------------------------------------------------

我知道

UPDATE table
SET flag = TRUE
ORDER BY created DESC
LIMIT 1;

会设置最近日期的标记,但我仍然坚持如何为每个组应用此标记。

我也试过了:

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;

1 个答案:

答案 0 :(得分:0)

也许尝试这样的事情:

someAsyncThing()