如何通过级联删除子记录数据时可以获得父记录数据

时间:2015-12-28 02:21:12

标签: postgresql triggers

考虑以下两个表:

CREATE TABLE public.parent
(
  id bigint NOT NULL DEFAULT nextval('parent_id_seq'::regclass),
  CONSTRAINT pk_parent PRIMARY KEY (id)
);

CREATE TABLE public.child
(
  child_id bigint NOT NULL DEFAULT nextval('child_child_id_seq'::regclass),
  parent_id bigint NOT NULL,
  CONSTRAINT pk_child PRIMARY KEY (child_id),
  CONSTRAINT inx_parent FOREIGN KEY (parent_id)
      REFERENCES public.parent (id) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE CASCADE
);

CREATE INDEX fki_child
  ON public.child
  USING btree
  (parent_id);

CREATE TRIGGER child_trg
  BEFORE DELETE
  ON public.child
  FOR EACH ROW
  EXECUTE PROCEDURE public.trg();

trg定义为:

CREATE OR REPLACE FUNCTION public.trg()
  RETURNS trigger AS
$BODY$BEGIN
    INSERT INTO temp
    SELECT p.id
    FROM parent p
    WHERE
        p.id = OLD.parent_id;
    return OLD;
END;$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

总结一下发生的事情,有两个简单的父子关系和一个级联的表。还有一个触发删除的孩子定义的触发器。当由于父子关系级联而删除子记录时,我需要在触发器中访问父项的数据。但我不能因为它们已被删除!有谁知道怎么做?

1 个答案:

答案 0 :(得分:1)

一种解决方案是在BEFORE DELETE 而不是 上创建parent触发器,可以看到所有数据

CREATE OR REPLACE FUNCTION public.trg_parent()
  RETURNS trigger AS
$func$
BEGIN
   INSERT INTO some_tbl (id)  -- use target list !!
   VALUES (OLD.parent_id);

   RETURN OLD;
END
$func$ LANGUAGE plpgsql;

CREATE TRIGGER parent_trg
BEFORE DELETE ON public.parent
FOR EACH ROW EXECUTE PROCEDURE public.trg_parent();