如何在PGSQL中使用多个条件更新多表列

时间:2019-06-04 05:39:37

标签: sql postgresql

我希望一个优化的查询根据不同的条件更新多个列。我已经写了一个查询,并且工作正常,但是我需要一个更优化的查询。 还有其他方法可以实现上述目标吗?

下面是我写的

UPDATE table1
      SET
      val1 = ( 
      CASE
            WHEN w_id = 287 THEN 'test1'
            WHEN w_id = 288 THEN 'test2'
            WHEN w_id = 469 THEN 'test3'
            WHEN w_id = 468 THEN 'test4'
            WHEN w_id IN (
                                        SELECT
                                            w_id
                                        FROM
                                            table1 t1
                                            INNER JOIN table2 t2 ON t1.id = t2.w_id 
            ) THEN 'test5'
        END ),
      val2 = ( 
      CASE
            WHEN w_id IN( 287, 288, 468, 469 ) THEN 'test6'
            WHEN w_id IN (
                                        SELECT
                                            w_id
                                        FROM
                                            table1 t1
                                            INNER JOIN table2 t2 ON t1.id = t2.w_id 
            ) THEN 'test6'
        END ),
              val3 = ( 
      CASE
            WHEN w_id IN( 287, 288, 468, 469 ) THEN 'test7'
            WHEN w_id IN (
                                        SELECT
                                            w_id
                                        FROM
                                            table1 t1
                                            INNER JOIN table2 t2 ON t1.id = t2.w_id
            ) THEN 'test7'
        END );

预先感谢

1 个答案:

答案 0 :(得分:0)

这是我目前唯一能想到的优化方法。

WITH CTE AS (
 SELECT
    w_id
 FROM
    table1 t1
    INNER JOIN table2 t2 ON t1.id = t2.w_id 
)
UPDATE Table1  
      SET
      Val1 = (
      CASE
            WHEN w_id = 287 THEN 'test1'
            WHEN w_id = 288 THEN 'test2'
            WHEN w_id = 469 THEN 'test3'
            WHEN w_id = 468 THEN 'test4'
            WHEN w_id IN (SELECT W_id from CTE) THEN 'test5'
      END ),
      val2 = (
      CASE
            WHEN w_id IN( 287, 288, 468, 469 ) THEN 'test6'
            WHEN w_id IN (SELECT W_ID from CTE) THEN 'test6'
      END ),
      val3 = ( 
      CASE
            WHEN w_id IN( 287, 288, 468, 469 ) THEN 'test7'
            WHEN w_id IN (SELECT W_ID FROM CTE) THEN 'test7'
      END );