简体   繁体   English

MySQL触发器从一个表中添加/减少,取决于另一个表中的条目

[英]MySQL Trigger adding/minusing from one table, depending on an entry in another

So, I have two tables: Transfers and Inventory.所以,我有两个表:转移和库存。

What I am trying to do is when something is entered into the Transfer table, it will change an entry in the Inventory table.我想要做的是当某些内容输入到 Transfer 表中时,它将更改 Inventory 表中的一个条目。

An example of what I need is:我需要的一个例子是:

Say there is a man named Dr Jones and another man named Dr Smith.假设有一个叫琼斯博士的人和另一个叫史密斯博士的人。 Dr Jones has £30 in his 'Total' and Dr Smith has £10.琼斯博士在他的“总计”中有 30 英镑,史密斯博士有 10 英镑。 Now, say Dr Jones gives Dr Smith £10, I need the Inventory table to -£10 on Dr Jones' account total, and +£10 onto Dr Smith's account total.现在,假设琼斯博士给史密斯博士 10 英镑,我需要库存表中琼斯博士的账户总额为 -10 英镑,史密斯博士的账户总额为 +10 英镑。 So therefore when you refresh the table, it states Dr Smith's balance in the total column as £20, and Dr Jones' balance as £20 now as well.因此,当您刷新表时,它在总列中指出 Smith 博士的余额为 20 英镑,而 Jones 博士的余额现在也为 20 英镑。

I want to do this through a trigger.我想通过触发器来做到这一点。 I currently have the following:我目前有以下几点:

DELIMITER $$
CREATE TRIGGER update_inventory_through_transfer AFTER INSERT ON Transfers
FOR EACH ROW
BEGIN
UPDATE Inventory
SET Inventory.total = SELECT SUM (IF (owner = NEW.owner, -total, total)) FROM Transfers WHERE owner = NEW.owner
END$$
DELIMITER;

Could anyone help me with where i'm going wrong?谁能帮我解决我哪里出错了? Thanks谢谢

The structure of your db is not clear from your question but assuming transfer knows the owner and who funds are being transferred to then the trigger should contain 2 straightforward updates, since a trigger is FOR EACH ROW then there is no need so sum the transfers.您的数据库的结构从您的问题中不清楚,但假设转移知道所有者以及资金被转移给谁,那么触发器应该包含 2 个直接更新,因为触发器是 FOR EACH ROW,所以不需要对转移进行总和。

drop table if exists transfer,inventory;

create table transfer (owner int,total int,tfr_to int);
create table inventory (owner int,total int);

insert into inventory values
(1,30),(2,10);

drop trigger if exists t; 
DELIMITER $$
CREATE TRIGGER t AFTER INSERT ON transfer
FOR EACH ROW
BEGIN
    UPDATE inventory t1
        SET t1.total = t1.total + new.total 
    where t1.owner = new.tfr_to;
    update inventory t1
        set t1.total = t1.total - new.total
    where t1.owner = new.owner;
END $$
DELIMITER ;

insert into transfer values (1,10,2);

select * from transfer;

+-------+-------+--------+
| owner | total | tfr_to |
+-------+-------+--------+
|     1 |    10 |      2 |
+-------+-------+--------+
1 row in set (0.02 sec)

select * from inventory;

+-------+-------+
| owner | total |
+-------+-------+
|     1 |    20 |
|     2 |    20 |
+-------+-------+
2 rows in set (0.00 sec)

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

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