sql(postgres)-如何创建一个触发器,将一个表中的两行相乘并在另一个表中将它们添加一行?

时间:2018-09-08 22:26:05

标签: java sql postgresql

我有两个表OrderItem和Orders。我想通过乘以数量和单价来更新OrderItem中每个插入的O​​rders表中的totalamount行。但是我无法创建正确的触发器。如何创建触发器。预先感谢!

这是我的订单表:

      CREATE TABLE public.orders
(
  orderid integer NOT NULL DEFAULT nextval('orders_orderid_seq'::regclass),
  ordernumber integer NOT NULL,
  customerid integer NOT NULL,
  totalamount numeric(12,4) NOT NULL,
  orderdate timestamp without time zone DEFAULT now(),
  CONSTRAINT orders_pk PRIMARY KEY (orderid),
  CONSTRAINT orders_fk FOREIGN KEY (customerid)
      REFERENCES public.customer (customerid) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE
)

这是我的Orderitem表:

 CREATE TABLE public.orderitem
(
  orderitemid integer NOT NULL DEFAULT nextval('orderitem_orderitemid_seq'::regclass),
  orderid integer NOT NULL,
  productid integer NOT NULL,
  unitprice numeric(12,4) NOT NULL DEFAULT 0,
  quantity integer NOT NULL,
  CONSTRAINT orderitem_pk PRIMARY KEY (orderitemid),
  CONSTRAINT orderitem_fk_order FOREIGN KEY (orderid)
      REFERENCES public.orders (orderid) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE,
  CONSTRAINT orderitem_fk_product FOREIGN KEY (productid)
      REFERENCES public.product (productid) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE
)
WITH (
  OIDS=FALSE
);
ALTER TABLE public.orderitem
  OWNER TO postgres;

-- Trigger: unitprice on public.orderitem

-- DROP TRIGGER unitprice ON public.orderitem;

CREATE TRIGGER unitprice
  AFTER INSERT
  ON public.orderitem
  FOR EACH ROW
  EXECUTE PROCEDURE public.transferunitprice();

和我尝试过的触发函数:

CREATE OR REPLACE FUNCTION public.increment_totalamount()
  RETURNS trigger AS
$BODY$
BEGIN
    SELECT Orderitem.unitprice * Orderitem.quantity + Orders.totalamount 
            INTO NEW.totalamount
    FROM Orderitem, Orders
    WHERE Orders.orderid = NEW.orderid;

    RETURN NEW;
END
$BODY$
  LANGUAGE plpgsql

我忘记添加触发器本身:

CREATE TRIGGER increment_totalamount
  BEFORE INSERT
  ON public.orderitem
  FOR EACH ROW
  EXECUTE PROCEDURE public.increment_totalamount();

1 个答案:

答案 0 :(得分:0)

您的触发器在orderitem表上,因此您需要在触发器内部调用常规更新语句。

与此类似的东西应该起作用

CREATE OR REPLACE FUNCTION update_order_price() RETURNS TRIGGER
AS $update_order_price$
    DECLARE
        delta numeric(14, 2)
    BEGIN
        -- Work out the increment/decrement amount(s).
        IF (TG_OP = 'INSERT') THEN
            delta = NEW.quantity * NEW.unitprice;
        ELSIF (TG_OP = 'UPDATE') THEN
            delta = NEW.quantity * NEW.unitprice - OLD.quantity * OLD.unitprice;
        ELSIF (TG_OP = 'DELETE') THEN
            delta = - OLD.quantity * OLD.unitprice;
        END IF;

        -- Update the order row
        UPDATE orders 
        SET totalamount = totalamount + delta
        WHERE id = OLD.orderid;

        RETURN NEW;
    END;
$update_order_price$ LANGUAGE plpgsql;