可以在postgres中同时更新一组连接表吗?

时间:2018-06-03 11:52:07

标签: postgresql

我有一个getter函数,它从一系列连接表中提取一个值,如下所示:

SELECT
    foo
FROM
    my_table AS mt
LEFT JOIN my_other_table AS mot ON mt.pkey = mot.fkey
LEFT JOIN my_other_other_table AS moot ON mot.pkey = moot.fkey
WHERE
    mt.pkey = 0

我想知道是否有办法以某种方式将其转换为setter函数,这将允许我更新此连接表的任何部分,并将这些更改传播回其原始表,即这样的事情:

UPDATE
    my_table AS mt
    LEFT JOIN my_other_table AS mot ON mt.pkey = mot.fkey
    LEFT JOIN my_other_other_table AS moot ON mot.pkey = moot.fkey
SET
    mt.some_val = 0
    mot.some_other_val = 1
    moot.some_other_other_val = 2
WHERE
    mt.pkey = 0

我意识到上面的代码实际上并不起作用,而且我相信这实际上并不可行,但我想不遗余力。有办法做我想做的事吗?或者它需要更复杂的plpgsql函数?

1 个答案:

答案 0 :(得分:1)

您不能在一个声明中,但您可以创建一个事务来进行全部或全部更改:

begin;

UPDATE
    my_table AS mt
SET
    mt.some_val = 0
WHERE
    mt.pkey = 0;


UPDATE
    my_other_table AS mot 
SET
    mot.some_other_val = 1
FROM my_table AS mt
WHERE
    mt.pkey = mot.fkey AND mt.pkey = 0;

UPDATE
    my_other_other_table AS moot
SET
    moot.some_other_other_val = 2
FROM my_table AS mt
    INNER JOIN my_other_table AS mot ON mt.pkey = mot.fkey
WHERE
    mot.pkey = moot.fkey AND mt.pkey = 0;

COMMIT;