【问题标题】:Create a trigger that subtracts 1 from a column in another table创建一个触发器,从另一个表的列中减去 1
【发布时间】:2021-06-01 19:23:17
【问题描述】:

我需要一个触发器,在称为数量表的列中减去 1,我已经研究了很多但我找不到解决方案(我知道这很简单),我有以下表格:

CREATE TABLE product 
(
    product_id number,
    price number,
    quantity number
)

CREATE TABLE sale 
(
    sale_id number,
    client_id number,
    product_id number
)

product表的数量列的值是从0开始的,假设我有50个产品的数量,我需要在有销售的时候这个产品的数量下降到49,你们可以吗?帮帮我?

【问题讨论】:

    标签: sql oracle triggers


    【解决方案1】:

    看起来sale 表缺少关键信息:已售商品的数量(数量)。所以:

    SQL> CREATE TABLE product (
      2    product_id number,
      3    price      number,
      4    quantity   number
      5  );
    
    Table created.
    
    SQL> CREATE TABLE sale (
      2   sale_id    number,
      3   client_id  number,
      4   product_id number,
      5   quantity   number           --> missing
      6  );
    
    Table created.
    

    触发器:

    SQL> create or replace trigger trg_ai_sale
      2    after insert on sale
      3    for each row
      4  begin
      5    update product p set
      6      p.quantity = p.quantity - :new.quantity
      7      where p.product_id = :new.product_id;
      8  end;
      9  /
    
    Trigger created.
    

    测试:product = 1 的起始数量为 50:

    SQL> insert into product (product_id, price, quantity) values (1, 100, 50);
    
    1 row created.
    

    让我们卖 1 件商品:

    SQL> insert into sale (sale_id, client_id, product_id, quantity) values (1, 1, 1, 1);
    
    1 row created.
    

    数量现在是 49:

    SQL> select * from product;
    
    PRODUCT_ID      PRICE   QUANTITY
    ---------- ---------- ----------
             1        100         49
    
    SQL>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-19
      • 1970-01-01
      • 2022-01-10
      • 2023-03-24
      相关资源
      最近更新 更多