假设我们有一张绘图表。
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
中删除相关修订,我不想离开孤立行。最有效的方法是什么?
最佳答案
要实现这一点,您可以在定义约束时使用 PostgreSQL 中的 CASCADE
关键字:
CONSTRAINT revisions_drawingid_fkey FOREIGN KEY (drawingid)
REFERENCES public.drawings (drawingid) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE CASCADE
现在,当删除绘图
中的行时,它将自动删除修订
中的孤立行。
关于sql - 删除行以及引用行 ID 的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56235342/