31

我有一张桌子:

mytable:
    id
    userID
    logDate
    lastLogDate

对于该表中的每一行,我想将“lastLogDate”列更新为每个用户的 logDate 的最大值......

从概念上讲,每个用户都应该有一个 lastLogDate = 返回的值:

select max(logDate) from mytable group by userID

有人可以帮我写更新声明吗?

4

6 回答 6

58

像这样的东西?

UPDATE mytable SET lastLogDate = t.maxDateForUser  
FROM  
(  
    SELECT userid, MAX(logDate) as maxDateForUser  
    FROM mytable  
    GROUP BY userId  
) t  
WHERE mytable.userid = t.userid
于 2012-12-14T15:41:24.837 回答
11

你可以这样做:

UPDATE t
SET t.logDate = t2.LatestDate
FROM YourTable t
INNER JOIN
(
    SELECT userID, MAX(LogDate) LatestDate
    FROM YourTable
    GROUP BY userID
) t2 ON t.userID = t2.userID; 
于 2012-12-14T15:40:31.857 回答
5

我不知道我是否理解正确。否则会更具体一点,但据我所知,你应该按照以下方式做一些事情:

UPDATE `mytable`
SET lastLogDate = (SELECT statement goes here)
WHERE ...
于 2012-12-14T15:38:46.070 回答
4
UPDATE mytable mT,
  (SELECT userid,
          MAX(logDate) AS maxDateForUser
   FROM mytable
   GROUP BY userId) t
SET mT.lastLogDate = t.maxDateForUser
WHERE mT.userid = t.userid;
于 2013-10-03T13:19:39.043 回答
3

以下更新声明应该做你正在寻找的

update mytable mt set  lastLogDate  = (select max(logDate) from  mytable where userID = mt.userID)
于 2012-12-14T15:51:10.403 回答
1

你可以像这样简单地编写一个嵌套查询


    Update  mytable a 
    set 
    a.lastLogDate = (select max(logDate) from mytable b
    where a.id=b.id)
    Where...;
于 2019-04-06T13:44:56.957 回答