database - INSERT 和多个 UPDATE 语句

标签 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;
(...)

最佳答案

我不明白为什么这不能通过单个 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;

关于database - INSERT 和多个 UPDATE 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33301011/

相关文章:

java - EclipseLink 2.3.3 无法更新 PostgreSQL 上的版本化实体

Django - order_by() 字符和数字

mysql - 在 mysql workbench 中启动迁移向导时出现问题

支付服务费用的网络应用程序数据库设计

mysql - 将具有 3 个表的旧 MySQL 迁移到 JSON

ruby-on-rails - rails 命名空间表单不会将数据写入数据库

postgresql - Golang GORM 中列的自动迁移问题

android - 如何从 Android 手机与服务器的数据库通信?

postgresql - 将表从一个数据库移动到另一个数据库 - 仅插入缺失的行

c# - 如何在实例化时将迁移应用到 EF 7 上下文?