user2670996
user2670996

Reputation: 2674

Update with subquery in MySql

I've two tables:

work (work_id (AI, PK), sent_date, received_date, visit_date)
history_work(id_history_work (AI, PK), work_id (FK), sent_date, reseived_date, visit_date)

Relationship shoud be 1->n.

I want to update work table so sent_date, received_date and visit_date shoud have the values of last inserted record in history_work table (last id_history value) with same work_id value.

Upvotes: 0

Views: 30

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269563

You can do this by using join. Join once to the history table. Join a second time to get the maximum id (which is presumably the most recent insertion).

update work w join
       history h
       on w.work_id = h.work_id join
       (select work_id, max(id_history_work) as maxihw
        from history
        group by work_id
       ) hw
       on hw.maxihw = h.id_work_history
    set w.sent_date = h.sent_date,
        w.received_date = h.received_date,
        w.visit_date = h.visit_date;

Upvotes: 1

Related Questions