INSERT有几个UPDATE语句

时间:2015-10-23 11:15:52

标签: database postgresql database-migration common-table-expression

使用Postgresql解决以下问题的最佳方法是什么?

对于每一行,我根据另一个表中的SELECT插入到文章表中,我想更新插入文章的某些列。

这是我目前的解决方案:


-- temporarily alter table to avoid not null issues
ALTER TABLE article ALTER COLUMN fk_article_unit DROP NOT NULL;
(...)

--create article and return inserted pks, store these in a temporary table so they can be used for all following updates
WITH articles AS (
  insert into article
  (
    ...
  )
  select
    ...
  from other_table
  where some_condition
  RETURNING pk
)
SELECT pk INTO temporary temp_articles
FROM articles;

-- update various fk for all newly created articles
UPDATE article
SET fk_article_type =
  (SELECT pk
  FROM article_type
  WHERE unique_id = 'service')
WHERE pk in (select pk from temp_articles);

UPDATE article
SET fk_article_type =
  (SELECT min(pk)
  FROM vat_code)
WHERE fk_article_type is null;

(... several more updates)

--readd no null constraint
ALTER TABLE article ALTER COLUMN fk_article_type SET NOT NULL;
(...)

1 个答案:

答案 0 :(得分:1)

我不明白为什么使用单个insert查询无法做到这一点。如果以下解决方案不适用,请提供有关您的数据模型的一些其他信息。

insert into article
(
  ...,
  fk_article_type
)
select
  ...,
  coalesce -- if first query is null, then the result of second will be used
  (
      ( -- 1st query
          select pk from article_type where unique_id= 'service'
      ),
      ( -- 2nd query
          select min(pk) from vat_code
      )
  )
from other_table
where some_condition
returning pk;