假设我有一本桌上杂志:
CREATE TABLE magazine
(
magazine_id integer NOT NULL DEFAULT nextval(('public.magazine_magazine_id_seq'::text)::regclass),
longname character varying(1000),
shortname character varying(200),
issn character varying(9),
CONSTRAINT pk_magazine PRIMARY KEY (magazine_id)
);
另一个表问题:
CREATE TABLE issue
(
issue_id integer NOT NULL DEFAULT nextval(('public.issue_issue_id_seq'::text)::regclass),
number integer,
year integer,
volume integer,
fk_magazine_id integer,
CONSTRAINT pk_issue PRIMARY KEY (issue_id),
CONSTRAINT fk_magazine_id FOREIGN KEY (fk_magazine_id)
REFERENCES magazine (magazine_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);
当前插入:
INSERT INTO magazine (longname,shotname,issn)
VALUES ('a long name','ee','1111-2222');
INSERT INTO issue (fk_magazine_id,number,year,volume)
VALUES (currval('magazine_magazine_id_seq'),'8','1982','6');
现在一行应该只插入到“杂志”中,如果它不存在的话。但是,如果它存在,则表 'issue' 需要获取已存在的行的 'magazine_id' 以建立引用。
我怎样才能做到这一点?
提前谢谢!