postgresql 仅将通过连接找到的不存在的记录插入到表中

mum43rcc  于 2022-12-23  发布在  PostgreSQL
关注(0)|答案(3)|浏览(156)

下面的查询查找匹配记录并返回与IN子句中的值匹配的"main"."item"."id"

select main.item_vendor.item_id
from main.item_vendor
join main.item on item.id = main.item_vendor.item_id
WHERE "main"."item"."id" IN ('188646', '200000699')

上面的查询只返回一个值,该值有188646的记录,而其他值则缺失。现在我需要使用上面的查询和main.item_vendor表中的INSERT值,仅用于此200000699
我如何将下面的INSERT查询插入到上面的连接查询中,这样它就可以只为那些不存在的项插入。这意味着我只想为200000699项ID插入main.item_vendor表,因为它不存在。

INSERT INTO "main"."item_vendor" ("item_id", "vendor_id", audit_by, currency_id )
VALUES (200000699, ?, ?, ?);
dsekswqp

dsekswqp1#

with wNotExists as (
  select main.item.id as notExistsId
    from main.item_vendor
    right join main.item on main.item.id = main.item_vendor.item_id
    where main.item_vendor.item_id is null
      and main.item.id IN ('188646', '200000699') -- comment this line for getting all "id" from "item" not exists in "item_vendor"
)
insert into main.item_vendor (item_id, vendor_id, audit_by, currency_id)
  select notExistsId, ?, ?, ?
    from wNotExists;
3npbholx

3npbholx2#

您可以使用CTE来确定项目ID,但item_id的插入i不存在

WITH CTE  as (
select item_vendor.item_id
from item_vendor
join item on item.id = item_vendor.item_id
WHERE "main"."item"."id" IN ('188646', '200000699'))
INSERT INTO "item_vendor" ("item_id", "vendor_id", audit_by, currency_id )
SELECT (item_id, 1, 1, 1)
FROM CTE c1
  WHERE NOT EXISTS ( SELECT 1 FROM item_vendor WHERE item_id = c1.item_id)
i5desfxk

i5desfxk3#

你不需要检查id是否已经存在。在item_id上放置一个唯一的索引或者使它成为主键。Postgres会自动检查这个值是否已经存在。如果你不做其他任何事情,这个条件会抛出一个异常。但是您可以通过扩展insert以包含on conflict子句来更改此设置。然后,您可以更新现有值或忽略(无提示)错误的传入行。因此,对于本例:

insert into "main"."item_vendor" ("item_id", "vendor_id", audit_by, currency_id )
     values ('188646', ?, ?, ?),('200000699', ?, ?, ?)
  on conflict (item_id) 
  do nothing;

相关问题