简体   繁体   中英

How to keep a self join of a table updated on update of the main table?

I have an update statement with a self join shown in the code below. Am supposed to get values from updated columns but I notice that the update on a1 does not reflect on joined a2.

UPDATE test.cashbook a1 
inner join test.cashbook a2 on a2.id = (CASE WHEN a1.id>1 then a1.id-1 
END)
SET a1.balanceBroughtFoward = a2.balanceCarriedDown, 
    a1.totalCash = a2.balanceCarriedDown + ifnull(a1.cashSale, 0), 
    a1.balanceCarriedDown = ifnull(a1.totalCash, 0) -(ifnull(a1.Lodgement, 0) + ifnull(a1.Expenses, 0))
    where a1.id > 1

The result I expect is to have the previous row's balanceCarriedFoward as my current row balanceBroughtFoward .

This perhaps is the need for the self join to same table as a2 but because only the first row ( a1.id = 1 ) has a balancecarriedFoward before the join, therefore only row two of a1 is updated though on subsequent rows of the original table ( a1 ) the update command updates balanceCarriedFoward during the update but I guess this values are not reflected in the self joined table ( a2 ) therefore giving null values for a1.balancbroughtFoward where row is > 2.

How can I get around this since I am limited to using MySQL 5.6?

I used a variable to achieve the need of joining a2 to a1 . Code below.

SET bc:= 0 UPDATE test.cashbook Set balanceBroughtFoward = bc, balanceCarriedFoward = (bc:= totalCash - (Lodgement + Expenses) )

The above code worked but then I now want to put the update statement in a trigger. it gives syntax error when I try. Am stock at this point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM