从tmp表插入,使用默认值

问题描述 投票:0回答:1

在 postgree 中,假设我有一个 tmp 表,其架构如下

tmp_data

id   |  name   | ...
--------------------
1    | '1_1'   | ...
null | 'test'  | ...
10   | 'other' | ...

我有初始表

data
,它具有相同的架构

id   |  name   | ...
--------------------
1    | '1'     | ...
2    | '2'     | ...

我想从初始tmp表更新插入到最终表,并返回所有id,所以我想写这个查询

insert into data (id, name, ...)
select id, name
from tmp_data
on conflict (id) update
set name = excluded.name
returning id

但问题是 id 是自动生成的,所以 - 我想插入该值(如果存在)(10)并生成如果不存在(null)

我尝试使用 select case if 列为 null 而不是默认值 - 但似乎默认值不能在 select 子句中使用

将查询拆分为 2 对我来说不是一个情况,因为我在 ef core 中使用该数据,并且我需要分批执行此操作 - 并获取 ids

我期待的结果

id   |  name   | ...
--------------------
1    | '1_1'   | ...
2    | '2'     | ...
3    | 'test'  | ...
10   | 'other' | ...

有什么选择吗?

postgresql
1个回答
0
投票

如果您无法使用 PG15 中引入的

merge
功能,您还可以在 ID 尚未设置时有条件地从序列中获取下一个 ID 值。

select coalesce(id, nextval(pg_get_serial_sequence('public.data','id')))
from temp_data;
© www.soinside.com 2019 - 2024. All rights reserved.