使用WITH和CASE更新 - PostgreSQL

时间:2016-02-01 23:03:38

标签: sql postgresql

我正在尝试将列的值更改为从其他两个表中的info构造的标题,但是我在运行数据时遇到了麻烦。我当前想要对所有条目执行此查询表。我在CASE上遇到语法错误,我无法弄清楚原因。

UPDATE campaigns AS cmp
    SET name = (
        WITH ptn AS (SELECT first_name, last_name FROM politicians WHERE id = cmp.politician_id),
            rc AS (SELECT office FROM races WHERE id = cmp.race_id)

        CASE
            WHEN rc.office IS NULL OR rc.office = '' THEN ptn.first_name || ' ' || ptn.last_name
            ELSE ptn.first_name || ' ' || ptn.last_name || ' for ' || rc.office
        END
    )

这是PostGres 9.4。这是我得到的错误

ERROR:  syntax error at or near "case"
LINE 5:   case
          ^

********** Error **********

ERROR: syntax error at or near "case"
SQL state: 42601
Character: 189

2 个答案:

答案 0 :(得分:22)

发生语法错误是因为您的联合相关子查询无效。在两个公用表表达式之后需要有一些select语句:

公用表表达式的基本结构是:

with ptn as (...),
  rc as (...)
select --<< you are missing this select here

但我认为整个事情可以写得更短更有效(如果我没有弄错的话)

UPDATE campaigns AS cmp
    SET name = CASE
                 WHEN rc.office IS NULL OR rc.office = '' THEN ptn.first_name || ' ' || ptn.last_name
                ELSE ptn.first_name || ' ' || ptn.last_name || ' for ' || rc.office
              END
from politicians ptn, races rc 
where ptn.id = cmp.politician_id
  and rc.id = cmp.race_id

答案 1 :(得分:1)

我倾向于使用from子句来执行此操作:

UPDATE campaigns AS cmp
    SET name = (CASE WHEN rc.office IS NULL OR rc.office = ''
                     THEN ptn.first_name || ' ' || ptn.last_name
                     ELSE ptn.first_name || ' ' || ptn.last_name || ' for ' || rc.office
                END)
    FROM politicians ptn, races rc
    WHERE ptn.id = cmp.politician_id and rc.id = cmp.race_id ;