简体   繁体   English

来自上一行的MySQL触发器

[英]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. 当我想要的结果是从上一行中减去它时,无法弄清楚它为什么要对sold进行一次统计。

Desired output: 所需的输出:

在此处输入图片说明

I'm thinking select quantity into prev_quantity is the culprit, but I cannot muster out a workable alternative. 我以为将select quantity into prev_quantity是罪魁祸首,但我无法提出可行的替代方案。

edit: here is an sqlfiddle - http://sqlfiddle.com/#!9/6cd76/2/0 编辑:这是一个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. 问题是您的LIMIT总是读取表的第一行,因为默认顺序是按主键升序排列的。 So prev_quantity is always 100. 因此prev_quantity始终为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. 由于两个插入的读数均为“ 50”,因此在计算“已售出”之前具有最后一个数量。

The Sold calculation is 50-40=10 for ID 15, and 50-30=20 for ID 16. 对于ID 15,Solded计算为50-40 = 10,对于ID 16为50-30 = 20。

The only way to protect against this is to lock the table during an INSERT: 防止这种情况的唯一方法是在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. 如果您要支持具有良好吞吐量的并发INSERT,则不建议这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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