解决以下 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/