postgresql 触发器更新当前日期在另一个表与Postgres 9

svmlkihl  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(3)|浏览(155)

我有两个名为salecustomer的表。我想创建一个触发器,在sale表中每次新插入时更新customer表上的列last_purchase
表customer:customer_id,name,last_销售,.
表销售:销售_id,客户_id,日期,.

CREATE TRIGGER update_last_sale BEFORE INSERT ON sale FOR EACH ROW EXECUTE...

字符串
我已经开始写了,但我不知道怎么写。
有人能帮帮我吗

hujrc8aj

hujrc8aj1#

CREATE FUNCTION update_customer_last_sale() RETURNS TRIGGER AS $$
BEGIN
    UPDATE customer SET last_sale=now() WHERE cutomer_id=NEW.customer_id;
    RETURN NEW;
END; $$
LANGUAGE plpgsql;

字符串
然后

CREATE TRIGGER update_last_sale
BEFORE INSERT ON sale
FOR EACH ROW EXECUTE update_customer_last_sale;


NEW是将要插入到销售表中的行。(对于更新行,NEW表示该行在更新后的外观,OLD表示该行在更新前的外观)。

hgc7kmma

hgc7kmma2#

基本上,我不认为存储冗余数据是一个好主意。customers中的最后一列_销售只是max(sales.销售_date)的聚合。
如果我们使用now()来访问customers.last_date,情况甚至会变得更糟。如果我们需要重新插入一些历史记录(例如重新计算去年的税收),会发生什么?这就是当你存储冗余数据时所得到的结果。

-- modelled after Erwin's version
SET search_path='tmp';

-- DROP TABLE customers CASCADE;
CREATE TABLE customers
    ( id INTEGER NOT NULL PRIMARY KEY
    , name VARCHAR
    , last_sale DATE
    );

-- DROP TABLE sales CASCADE;
CREATE TABLE sales
    ( id INTEGER NOT NULL PRIMARY KEY
    , customer_id INTEGER REFERENCES customers(id)
    , saledate DATE NOT NULL
    );

CREATE OR REPLACE FUNCTION update_customer_last_sale() RETURNS TRIGGER AS $meat$
BEGIN
    UPDATE customers cu
    -- SET last_sale = now() WHERE id=NEW.customer_id
    SET last_sale = (
        SELECT MAX(saledate) FROM sales sa
        WHERE sa.customer_id=cu.id
        )   
    WHERE cu.id=NEW.customer_id
    ;
    RETURN NEW;
END; $meat$
LANGUAGE plpgsql;

CREATE TRIGGER update_last_sale
    AFTER INSERT ON sales
    FOR EACH ROW
    EXECUTE PROCEDURE update_customer_last_sale();

INSERT INTO customers(id,name,last_sale) VALUES(1, 'Dick', NULL),(2, 'Sue', NULL),(3, 'Bill', NULL);

INSERT INTO sales(id,customer_id,saledate) VALUES (1,1,'1900-01-01'),(2,1,'1950-01-01'),(3,2,'2011-12-15');

SELECT * FROM customers;

SELECT * FROM sales;

字符串
结果:

id | name | last_sale  
----+------+------------
  3 | Bill | 
  1 | Dick | 1950-01-01
  2 | Sue  | 2011-12-15
(3 rows)

 id | customer_id |  saledate  
----+-------------+------------
  1 |           1 | 1900-01-01
  2 |           1 | 1950-01-01
  3 |           2 | 2011-12-15
(3 rows)

niknxzdl

niknxzdl3#

我觉得你想要这里的规矩。

CREATE RULE therule AS ON INSERT TO sale DO ALSO
    (UPDATE customer SET customer.last_sale = now()
           WHERE customer.customer_id=NEW.customer_id);

字符串

编辑:但请在评论中查看讨论。

相关问题