说我们有一张图纸表。
CREATE TABLE public.drawings
(
drawingid integer NOT NULL DEFAULT nextval('drawings_drawingid_seq'::regclass),
name text,
discipline text,
type text,
CONSTRAINT drawings_pkey PRIMARY KEY (drawingid)
);
我们有一个修订表,用于存储每个图形的所有修订数据。
CREATE TABLE public.revisions
(
revisionid integer NOT NULL DEFAULT nextval('revisions_revisionid_seq'::regclass),
drawingid integer,
sequence integer,
revision text,
state text,
meta jsonb,
"Description" text,
"TB_DRAWING_NO" text,
"File Name" text,
"ATT_CADTYPE" text,
"PW_SUITABILITY" text,
"TB_TITLE_LINE_1" text,
"TB_TITLE_LINE_2" text,
"TB_TITLE_LINE_3" text,
"TB_TITLE_LINE_4" text,
--snip
"RV_APPDATE10" timestamp without time zone,
"RV_APPDATE11" timestamp without time zone,
"RV_APPDATE12" timestamp without time zone,
"File Updated" timestamp without time zone,
"Updated" timestamp without time zone,
"Created" timestamp without time zone,
"File Updated By" text,
"Updated By" text,
"Created By" text,
CONSTRAINT revisions_pkey PRIMARY KEY (revisionid),
CONSTRAINT revisions_drawingid_fkey FOREIGN KEY (drawingid)
REFERENCES public.drawings (drawingid) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
说我想从drawings
表中删除很多行,但是我也想从revisions
中删除相关的修订,我不想留下孤立的行。最有效的方法是什么?
答案 0 :(得分:2)
要达到这个目的,可以在定义约束时使用PostgreSQL的CASCADE
关键字:
CONSTRAINT revisions_drawingid_fkey FOREIGN KEY (drawingid)
REFERENCES public.drawings (drawingid) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE CASCADE
现在,当删除drawings
中的一行时,它将自动删除revisions
中的孤立行。