如果其他表中的列与值匹配,则更新表中的列

时间:2019-09-27 14:47:55

标签: sql postgresql

我想更新下表

CREATE TABLE public.drawings
(
  drawing_id integer NOT NULL DEFAULT nextval('drawings_drawing_id_seq'::regclass),
  drawing_number text,
  discipline text,
  type text,
  ownership text,
  required_asbuilt boolean DEFAULT false,
  service_type text,
  design_requirement text,
  current_asbuilt_approved boolean,
  CONSTRAINT drawings_pkey PRIMARY KEY (drawing_id)
)

设置required_asbuilt=false。我想将drawing_id列与drawing_id中的revisions列相匹配并且如果eb_suitability_status='obsolete'出现在revision的某一行中时,将其设置为false。

CREATE TABLE public.revisions
(
  revision_id integer NOT NULL DEFAULT nextval('revisions_revision_id_seq'::regclass),
  drawing_id integer,
  basis_revision text,
  filename text,
  sequence integer,
  title text,
  rev_1 text,
  revision_date date,
  suitability text,
  design_status text,
  revision_note text,
  eb_url text,
  eb_suitability_status text,
  eb_review_acceptance_status text,
  CONSTRAINT revisions_pkey PRIMARY KEY (revision_id),
  CONSTRAINT revisions_drawing_id_fkey FOREIGN KEY (drawing_id)
      REFERENCES public.drawings (drawing_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE
)

实现此目标的最佳方法是什么?使用Postgresql 10。

1 个答案:

答案 0 :(得分:1)

您只是想要一个update吗?

update drawings d
    set required_asbuilt = false
    where exists (select 1
                  from revisions r
                  where r.drawing_id = d.drawing_id and
                        r.eb_suitability_status = 'obsolete'
                 );

在其他所有情况下(如果实际上要将其设置为true(即更新 all 行),则可以将exists放在{ {1}}:

set