创建一个从另一个 table 中的列中减去 1 的触发器

Create a trigger that subtracts 1 from a column in another table

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

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

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

产品数量栏的值table以0开头,假设我有一个产品的数量是50,我需要在有促销的时候这个产品的数量下降到49,你们能帮帮我吗?

看起来 sale table 遗漏了关键信息:已售商品的数量(数量)。所以:

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.

测试:产品 = 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>