Postgresql如何使用一组插入的id来插入到另一个表?

j2cgzkjk  于 2023-06-29  发布在  PostgreSQL
关注(0)|答案(1)|浏览(142)

我想要的:如果存在具有相同唯一性(doctor_id,year,month)的记录,我们需要通过输入sum值增加sum
我正在尝试这个SQL查询:

with rows as (
    insert into mis_doctor_stats (doctor_id, year, month, sum)
        values (1, 2025, 3, 100),
               (1, 2021, 4, 6)
        on conflict (doctor_id, year, month) do update set sum = mis_doctor_stats.sum + excluded.sum
        returning id)
insert
into mis_doctor_stats_files(file_id, stats_id)
select 4, rows.id
from rows;

但还是得到了错误:FROM预期,得到';”
screenshot

dldeef67

dldeef671#

正如@Bruno严格说的,问题出在alias_name中,我试图使用保留关键字rows
在我的案例中正确的解决方案:

with cte as (
    insert into mis_doctor_stats (doctor_id, year, month, sum)
        values (1, 2020, 3, 100),
               (1, 2023, 4, 6)
        on conflict (doctor_id, year, month) do update set sum = mis_doctor_stats.sum + excluded.sum
        returning id)
insert
into mis_doctor_stats_files(file_id, stats_id)
select 4, cte.id
from cte
on conflict do nothing;

相关问题