How to update final associated record I have list of items that are belongs to orders. Each item has fee_percentage field. and the sum of items is total_price in orders table.

What I want to achieve? 
I want to update the fee field of last associated items.

_________________________      __________________________________________
| order ID | total_price|      | id | order_id | fee_percentage |  fee  |
-------------------------      ------------------------------------------
|   334    |     425    |      |  1 |   334    |      50        |  212  |
  # The `fee` should be 213 =&gt; |  2 |   334    |      50        |  212  | 


As you can see the sum of items will be 424. I want to add the remaining fee to the last item fee. (So the fee of item id 2 should be 213).

Any help please?

This is what I have written so far

UPDATE items AS i
LEFT JOIN orders AS o ON o.order_id = b.order_id
LEFT JOIN (
    SELECT order_id, SUM(fee) AS sum_fee
    FROM items 
    GROUP BY order_id
    WHERE deleted = 0
) AS b1 ON b1.order_id = b.order_id
SET b.fee = b.fee + (o.total_price - b1.sum_fee)
WHERE b.deleted = 0;
Check it here: http://rextester.com/MGKS16637

I'm getting max(Id) and difference between sum(fee) and total price from items table. If this value is &lt;> 0, then update the item with id=max(id).

update items
       join (select max(i.id) mid, o.totalPrice - sum(i.fee) as diff
           from items i
           inner join orders o on i.order_Id = o.orderId
           group by i.order_id
           order by i.order_id, i.id) v
       on items.id = v.mid
set items.fee = items.fee + v.diff
where v.diff &lt;&gt; 0;