我有一张桌子:
mytable:
id
userID
logDate
lastLogDate
对于该表中的每一行,我想将'lastLogDate'列更新为每个用户的logDate的最大值...
从概念上讲,每个用户都应该有一个lastLogDate =返回的值:
select max(logDate) from mytable group by userID
有人可以帮我写一下更新声明吗?
答案 0 :(得分:48)
这样的东西?
UPDATE mytable SET lastLogDate = t.maxDateForUser
FROM
(
SELECT userid, MAX(logDate) as maxDateForUser
FROM mytable
GROUP BY userId
) t
WHERE mytable.userid = t.userid
答案 1 :(得分:10)
你可以这样做:
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;
答案 2 :(得分:5)
我不知道我是否理解正确。否则会更具体,但从我得到的,你应该做的事情:
UPDATE `mytable`
SET lastLogDate = (SELECT statement goes here)
WHERE ...
答案 3 :(得分:3)
以下更新声明应该按照您要求的方式进行
update mytable mt set lastLogDate = (select max(logDate) from mytable where userID = mt.userID)
答案 4 :(得分:2)
更新mytable mT,
(SELECT userid,MAX(logDate)as maxDateForUser FROM mytable GROUP BY userId) t
SET mT.lastLogDate = t.maxDateForUser WHERE mT.userid = t.userid;
答案 5 :(得分:1)
您可以像这样简单地编写一个嵌套查询
Update mytable a
set
a.lastLogDate = (select max(logDate) from mytable b
where a.id=b.id)
Where...;