SQL Postgres-在不存在的地方插入

时间:2019-03-12 14:29:02

标签: sql postgresql insert-into

如果给定id_client不存在的行(在PostgreSQL中),我想在tableA中插入新行:

INSERT INTO tableA(id_client, opr_wpr, data_wpr)
    VALUES((SELECT id_client FROM tableB WHERE id = 272), 212121, now());

我该怎么做?

3 个答案:

答案 0 :(得分:2)

赞:

INSERT INTO tableA(id_client, opr_wpr, data_wpr)
SELECT b.id_client, 212121, now() 
FROM 
  tableB b 
  LEFT JOIN tableA a 
  ON b.id_client = a.id_client
WHERE b.id = 272 AND a.id_client is null;

在以下情况下,select查询将仅返回一行:

  • 表B中ID为272的记录
  • 表A中没有与该b.id_client相关的记录

没有行时,左联接将在tableA.id_client中返回null。在该id_client的tableA中插入一行后,左联接将停止返回null并返回相关的行。在哪里条件是a.id_client为null,而不再是null。这将导致SELECT语句返回0行,这意味着未插入任何内容

答案 1 :(得分:1)

使用SELECT作为INSERT的来源:

with data as (
  SELECT id_client, 212121 as opr_wpr, now() as data_wpr
  FROM tableB 
  WHERE id = 272
)
INSERT INTO tablea(id_client, opr_wpr, data_wpr)
SELECT *
FROM data
WHERE not exists (select * 
                  from tablea
                  where id_client in (select id_client
                                      from data));

使用公用表表达式,因此仅需提供一次源条件。


或者,如果您对tablea.id_client有唯一的约束,则只需执行以下操作:

INSERT INTO tablea(id_client, opr_wpr, data_wpr)
SELECT id_client, 212121, now()
FROM tableB 
WHERE id = 272
on conflict (id_client) do nothing;

答案 2 :(得分:0)

INSERT INTO tableA(id_client, opr_wpr, data_wpr)
    VALUES((SELECT id_client FROM tableB WHERE id != null), 212121, now());