如何在SQL中更新每组的最大行数

时间:2014-03-09 16:20:43

标签: mysql

我刚刚将“默认”列添加到了我的数据库中。我试图根据每个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,将'default'列设置为'1',每个'accountId'只有一次基于最新的'addDate'。

2 个答案:

答案 0 :(得分:0)

试试这个

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

DEMO HERE

答案 1 :(得分:0)

UPDATE table1 x
  LEFT
  JOIN table1 y
    ON y.accountid = x.accountid
   AND y.adddate > x.adddate
   SET x.default = 1
 WHERE y.id IS NULL;

或(更快)

UPDATE table1 x
 JOIN 
    ( SELECT accountid  
           , MAX(addDate) max_adddate 
        FROM table1 
       GROUP 
          BY accountid
    ) y
   ON y.accountId = x.accountId
  AND y.max_adddate = x.adddate
  SET x.default = 1;