【问题标题】:Trigger update product quantity触发更新产品数量
【发布时间】:2021-09-29 02:51:59
【问题描述】:

我正在尝试更新 product_stock 表中的 Product 项目数量(当 Product 表中发生 UPDATE 时,它将更新 product_stock 表中的 Product 数量)。但是错误正在运行 -> 错误代码:1054。'where 子句'中的未知列'product.id_product'

CREATE TABLE IF NOT EXISTS `product`(
    `id_product`INT(11) NOT NULL AUTO_INCREMENT,    
    `unitarya_value`DECIMAL NOT NULL,    
    `minimum_quantity` INT(11) NOT NULL,    
    PRIMARY KEY(`id_product`))    
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;


CREATE TABLE IF NOT EXISTS `stock_product`(
    `id_stock_product`INT(11) NOT NULL AUTO_INCREMENT,    
    `current_quantity`INT(11) NOT NULL,   
    `id_product`INT(11) NOT NULL,    
    PRIMARY KEY(`id_stock_product`),
    FOREIGN KEY(`id_product`)
    REFERENCES `product` (`id_product`)    
    ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;

DELIMITER $$
CREATE TRIGGER updateProductquantity
BEFORE UPDATE ON product
FOR EACH ROW
BEGIN
    DECLARE qtt INT DEFAULT 50;
    UPDATE stock_product set current_quantity = current_quantity + qtt
    WHERE stock_product.id_product = product.id_product ; 
END; $$

【问题讨论】:

    标签: mysql sql database


    【解决方案1】:

    BEFORE UPDATE 触发器中,product 表中的列以NEW.columnOLD.column 为前缀,而不是表名本身,因此WHERE 子句的最后一部分可能是:

    WHERE stock_product.id_product = NEW.id_product ;
    

    另外,附带说明一下:除非有其他带有 qtt 变量的计划,否则您可以在不带变量的 SET 子句中使用 50 值:

    UPDATE stock_product SET current_quantity = current_quantity + 50
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      • 1970-01-01
      • 2020-04-19
      相关资源
      最近更新 更多