Reputation: 521
Lets say I have two tables
table_1
ID Name Status
1 John
2 Peter
3 Smith
table_2
ID UID Status UpdateDate
1 1 B 2010-05-05
2 1 C 2011-03-02
3 3 C 2011-03-02
4 2 A 2011-03-02
What is the correct statement to update Status
on table_1
according to UpdateDate
on table_2
.
Result should be like this
table_1
ID Name Status
1 John C
2 Peter A
3 Smith C
Thanks.
Upvotes: 2
Views: 397
Reputation: 25277
UPDATE table_1 SET Status = (
SELECT Status FROM table_2
WHERE UID = table_1.ID
ORDER BY UpdateDate desc
LIMIT 1
);
Upvotes: 1
Reputation: 9697
To get the status for each UID:
SELECT UID, Status
FROM (
SELECT UID, MAX(UpdateDate) LastUpdateDate
FROM table_2
GROUP BY UID
) l
JOIN table_2 t ON t.UID = l.UID AND t.UpdateDate = l.LastUpdateDate
To update:
UPDATE table_1 SET Status = l.Status
FROM table_1 t
JOIN (
SELECT UID, Status
FROM (
SELECT UID, MAX(UpdateDate) LastUpdateDate
FROM table_2
GROUP BY UID
) l
JOIN table_2 t ON t.UID = l.UID AND t.UpdateDate = l.LastUpdateDate
) l ON l.UID = t.ID
Upvotes: 0