代码之家  ›  专栏  ›  技术社区  ›  wfgeo

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

  •  0
  • wfgeo  · 技术社区  · 8 年前

    我有一个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 回复  |  直到 8 年前
        1
  •  1
  •   wargre    8 年前

    不能在一条语句中使用,但可以创建一个事务来执行“全部”或“无”更改:

    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;