Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update statement using nested query

Tags:

sql

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?

like image 588
user85116 Avatar asked Dec 14 '12 15:12

user85116


People also ask

Can we use update statement in subquery?

UPDATE operations with subqueries that reference the same table object are supported only if all of the following conditions are true: The subquery either returns a single row, or else has no correlated column references. The subquery is in the UPDATE statement WHERE clause, using Condition with Subquery syntax.

Can we use subquery in update statement in Oracle?

UPDATE Subquery Finally, you can use a subquery in an UPDATE statement for the table to be updated. In the previous examples, we have just used the product table. However, you can use a subquery instead of the product table, which will return a result set that can be updated.

How do you write a record update query?

UPDATE table_name SET column1 = value1, column2 = value2,... WHERE condition; table_name: name of the table column1: name of first , second, third column.... value1: new value for first, second, third column.... condition: condition to select the rows for which the values of columns needs to be updated.

Can we use update and SELECT together in SQL?

Unfortunately, SQL does not allow more than one SET condition per query. The UPDATE statement lists the target table, the SET statement specifies the column on that target table and the SELECT statement lists the source table and column.


2 Answers

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 
like image 189
DWright Avatar answered Oct 18 '22 19:10

DWright


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;  
like image 31
Mahmoud Gamal Avatar answered Oct 18 '22 21:10

Mahmoud Gamal