如何在符合特定 if 条件的 if-then-else 块内执行 mysql 命令

问题描述 投票:0回答:1

我有一个名为“tbl_sales_details”的 MySQL 表作为“table1”

___________________________
| tbl_sales_details        |
___________________________
| sales_id   PK varchar(20)|
| product_code varchar(20) |
| Qty  INT                 |
| Amount DOUBLE            |
____________________________

我还有一个名为“tbl_return_sales_details”的表作为“table2”

___________________________
| tbl_return_sales_details|
___________________________
| return_id  varchar(20)   |
| sales_id   FK varchar(20)|
| product_code varchar(20) |
| returned_Qty  INT        |
| returned_Amount DOUBLE   |
____________________________

现在我想要实现的是:

  1. 每当table2中有新插入的数据时,具有相同的sales_id和product_code就会执行:

    UPDATE table1 set qty = qty - NEW.returned_qty WHERE sales_id = NEW.sales_id AND product_code = NEW.product_code

  2. 但是如果return_qty(来自table2)等于qty(来自table1) 执行:

    delete from table1 where sales_id = NEW.sales_id AND product_code = NEW.product_code

  3. 我已经有了我开始的代码,但语法有错误。

CREATE TRIGGER table2_trigger AFTER INSERT ON table2 FOR EACH ROW
BEGIN
    declare sales_qty int;
    declare return_qty int;
    set sales_qty = (select qty from tbl_sales_details where sales_id = new.sales_id);
    set return_qty = (select returned_qty from tbl_returned_sales_details where sales_id = new.sales_id);
    if (sales_qty = return_qty)
    then
        delete from tbl_sales_details where sales_id = new.sales_id;
    else
        update tbl_sales_details set qty = qty - returned_qty, amount = amount - returned_amount where sales_id = new.sales_id;
    end if;
END

    
mysql triggers
1个回答
0
投票

解决方案:

当引用表中插入或更新的新值时,我通过在 MySQL 触发器中使用

new
关键字找到了问题的解决方案。

在 MySQL 触发器中,

NEW
关键字用于在
INSERT
UPDATE
操作后引用列的新值。这是解决我的问题的关键。

触发代码示例:

BEGIN
DECLARE sales_qty INT;
DECLARE return_qty INT;

-- Get the current sales quantity
SET sales_qty = (SELECT qty FROM tbl_sales_details WHERE sales_id = NEW.sales_id);

-- Get the returned quantity
SET return_qty = (SELECT returned_qty FROM tbl_returned_sales_details WHERE sales_id = NEW.sales_id);

-- Check if the quantities match
IF(sales_qty = return_qty) THEN
    -- If they match, delete the record from tbl_sales_details
    DELETE FROM tbl_sales_details WHERE sales_id = NEW.sales_id;
ELSE
    -- If not, update the sales quantity and amount based on the returned quantities
    UPDATE tbl_sales_details
    SET qty = qty - NEW.returned_qty,
        amount = amount - NEW.returned_amount
    WHERE sales_id = NEW.sales_id;
END IF;

结束;

要点:

  1. NEW
    关键字用于引用触发器中新插入或更新的数据。例如,
    NEW.sales_id
    NEW.returned_qty
    NEW.returned_amount
  2. 使用
    NEW
    确保您正在使用正在插入或更新的新数据,而不是更改之前的旧数据。
  3. 这解决了我在正确引用触发器主体中的新值时所面临的问题。 您可以在官方文档中了解有关 MySQL 触发器中 NEW 和 OLD 关键字的更多信息:MySQL 触发器语法和示例。
© www.soinside.com 2019 - 2024. All rights reserved.