在一个Postgresql中更新多个表

时间:2019-05-16 08:50:06

标签: php postgresql

我有三个表A,B,C。表B和表C由表A的ID组成外键。

更新Form时,将通过识别外键将数据更新到这三个表中。

CREATE TABLE A(
   id serial PRIMARY KEY, 
   id_theme_thesaurus  text,
   id_series text,
   id_geo_form text
);

CREATE  TABLE B(
   id  serial PRIMARY KEY,
   meta_id int,
   cit_title text,
   cit_pub_date text
);

CREATE  TABLE C(
   id serial PRIMARY KEY,
   meta_id int,
   id_originator text
);

这是我的更新声明

UPDATE B AS c
SET cit_pub_date = '2016'
FROM t_metadata AS m
WHERE c.meta_id = m.id
AND m.id = '2';

UPDATE C AS o
SET id_originator = 'UN'
FROM t_metadata AS m
WHERE o.meta_id = m.id
AND m.id = '2';

如何将这两个UPDATE语句合并为一个连接?

1 个答案:

答案 0 :(得分:0)

CTE(with子句)可以帮助解决您的问题,它将在一个sql中实现更新两个表的功能。如下:

with tmp1 as (
UPDATE B AS c SET cit_pub_date = '2016' FROM t_metadata AS m WHERE c.meta_id = m.id AND m.id = '2'
)
,tmp2 as (
UPDATE C AS o SET id_originator = 'UN' FROM t_metadata AS m WHERE o.meta_id = m.id AND m.id = '2' returning o.meta_id
)
select * from tmp2