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