Database 插入多个UPDATE语句
用Postgresql解决以下问题的最佳方法是什么 对于我根据从另一个表中选择插入到文章表中的每一行,我希望更新插入文章的某些列 这是我当前的解决方案:Database 插入多个UPDATE语句,database,postgresql,database-migration,common-table-expression,Database,Postgresql,Database Migration,Common Table Expression,用Postgresql解决以下问题的最佳方法是什么 对于我根据从另一个表中选择插入到文章表中的每一行,我希望更新插入文章的某些列 这是我当前的解决方案: -- 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 t
-- 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;
插入是否为所有新行保留
fk_article_type
null?你是在问如何将以下两个更新直接合并到插件中吗?嗨,丹尼尔。对于某些行,插入可能会将fk_article_type保留为null。我不认为在我复杂的示例中合并更新会起作用(在这个简化的示例中,我想这是可能的)。我想我只是想知道我的解决方案是否是一个“好”的解决方案,或者我是否在做一些相当愚蠢的事,因为有一个更简单/更好/更干净的解决方案。。。切换NOTNULL约束需要对表(不包括读卡器)进行强锁定,当将其放回时,它将重新检查整个表。在高并发性或大表上下文中,这并不理想。在我的例子中,这应该不是问题,因为涉及的表通常不超过100行,并且我们只在迁移期间使用此查询。但我仍然很想知道如何在不切换NOTNULL约束的情况下实现这一点。全合一查询?那么如何处理fk_article_类型的双重更新呢?谢谢:)我现在无法尝试,但它看起来很棒:)。我把这条路弄得太复杂了。一旦我能试一下,我就会接受答案:)。