update statement using nested query

2020-02-08 10:06发布

I have a table:

mytable:
    id
    userID
    logDate
    lastLogDate

For every row in that table, I want to update the 'lastLogDate' column to be the max value of logDate on a per user basis...

Conceptually, each user should have a lastLogDate = the value that is returned by:

select max(logDate) from mytable group by userID

Can somebody help me write the update statement for that?

标签: sql
6条回答
男人必须洒脱
2楼-- · 2020-02-08 10:37

Something like this?

UPDATE mytable SET lastLogDate = t.maxDateForUser  
FROM  
(  
    SELECT userid, MAX(logDate) as maxDateForUser  
    FROM mytable  
    GROUP BY userId  
) t  
WHERE mytable.userid = t.userid
查看更多
欢心
3楼-- · 2020-02-08 10:44

You can do this:

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; 
查看更多
甜甜的少女心
4楼-- · 2020-02-08 10:44

you can simply write a nested query like this


    Update  mytable a 
    set 
    a.lastLogDate = (select max(logDate) from mytable b
    where a.id=b.id)
    Where...;
查看更多
Emotional °昔
5楼-- · 2020-02-08 10:49
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;
查看更多
Lonely孤独者°
6楼-- · 2020-02-08 10:52

I don’t know if I understood you correctly. Otherwise be a bit more specific, but from what I get, you should do something along the lines of:

UPDATE `mytable`
SET lastLogDate = (SELECT statement goes here)
WHERE ...
查看更多
家丑人穷心不美
7楼-- · 2020-02-08 10:52

Following update statement should do what you are looking for

update mytable mt set  lastLogDate  = (select max(logDate) from  mytable where userID = mt.userID)
查看更多
登录 后发表回答