简体   繁体   中英

MySQL Trigger From Previous Row

Been working on this for hours.. am so close.

CREATE TRIGGER `sold_diff` BEFORE INSERT ON `inventory_history`
FOR EACH ROW begin
declare prev_quantity int(11) default 0;

select quantity
into prev_quantity 
from inventory_history
limit 1;

set NEW.sold = prev_quantity - NEW.quantity;
end

Here's the result:

在此处输入图片说明

Cannot figure out why it's doing a running tally on sold , when my desired result is to just subtracting it from the previous row.

Desired output:

在此处输入图片说明

I'm thinking select quantity into prev_quantity is the culprit, but I cannot muster out a workable alternative.

edit: here is an sqlfiddle - http://sqlfiddle.com/#!9/6cd76/2/0

The problem is your LIMIT is always reading the first row in the table, because the default order is by primary key, ascending. So prev_quantity is always 100.

To get the last quantity, you need to use:

select quantity
into prev_quantity 
from inventory_history
order by id desc
limit 1;

However, I caution you that this is susceptible to a race condition. Two concurrent inserts to the table could read the same value as the last quantity, and then calculate their new sold total based on that, and you'd get the following:

ID SKU    Quantity Sold
15 Filter 40       10
16 Filter 30       20

Because both inserts read "50" has the last quantity before calculating Sold.

The Sold calculation is 50-40=10 for ID 15, and 50-30=20 for ID 16.

The only way to protect against this is to lock the table during an INSERT:

LOCK TABLE inventory_history WRITE;
INSERT INTO inventory_history VALUES (...);
UNLOCK TABLES;

I don't recommend doing that if you want to support concurrent INSERTs with good throughput.

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