CASE,WHEN,THEN,UPDATE

时间:2017-07-08 03:24:17

标签: postgresql

我遇到此问题,如果copy_on_write.id中没有记录,则UPDATE listings SET images = (SELECT images FROM new_vals)会运行,并在没有任何内容的情况下清除listings.images

因此,如果UPDATE listings存在,我尝试使用条件仅运行copy_on_write.images

现在我得到:

psql:queries/copy-to-source.sh:20: ERROR:  syntax error at or near "CASE"
LINE 10:       CASE WHEN images <> 
WITH
  new_vals AS (
    SELECT *
    FROM copy_on_write
    WHERE copy_on_write.posted_by = 102550922::text
      AND copy_on_write.id = 4
  ),

  updates AS (
    SELECT images FROM new_vals,
      CASE WHEN images <> ''
        THEN UPDATE listings SET images = (SELECT images FROM new_vals)
      END
  )
SELECT internal_id FROM new_vals

1 个答案:

答案 0 :(得分:4)

您可以像这样使用parent CTE:

updates

请注意:

  • 您的... updates AS ( UPDATE listings SET images = new_vals.images FROM new_vals WHERE new_vals.images <> '' ) .... CTE应始终返回最多一条记录,否则这将无效。

  • 这也不会更新new_vals表,如果listings返回images列,但它是空字符串(或null)。如果在这种情况下您仍然需要运行更新,请完全删除new_vals

  • 此外,此语句还将更新所有WHERE new_vals.images <> ''条记录。你真的想要这个吗?