我刚刚在数据库中添加了“默认”列。我试图基于每个accountId的最新“ addDate”将默认值设置为“ 1”。

+----+-----------+--------------------+--------+
| id | accountId |      addDate       | default|
+----+-----------+--------------------+--------+
| 1  | 45        |2012-02-29 08:41:59 |        |
| 2  | 55        |2012-03-29 08:41:59 |        |
| 3  | 45        |2012-04-29 08:41:59 |        |
| 4  | 55        |2012-05-29 08:41:59 |        |
| 5  | 60        |2012-05-29 08:41:59 |        |
+----+-----------+--------------------+--------+


我发现我可以通过使用=>隔离正确的行

select * from tble1
where addDate = (select max(addDate) from tble1 as sl where sl.accountId = tble1.accountId);


我需要能够运行一个UPDATE,将每个'accountId'的'default'列设置为'1'仅1次,并以最新的'addDate'为基础。

最佳答案

尝试这个

 UPdate Table1
 SET `default` = 1
 where addDate in (select * from (
                               select max(addDate) from table1 as sl group by accountId)t
                                 )


DEMO HERE

10-06 03:08