Postgres:如果 table 中不存在记录,则插入记录时出现问题

Postgres: Problem INSERTING records if they does not exist already in a table

我有两个 table:

时间Table:planning.env_seleccion_envase seleccionado_temp(每天更新一次,目前有500条记录)

有成效Table: planning.env_seleccion_envase_seleccionado(整合全年数据,目前有0条记录)

为了仅将新记录从临时 table 插入到生产 table 我进行了查询,这是我的尝试:

INSERT INTO planning.env_seleccion_envase_seleccionado(centro, sku, texto_breve_material, movimiento, almacen, cantidad, unidad_medida_base, fecha_contabilizacion, fecha_entrada, sag, uen, drv, cupo, tipo_envase, cupo_agrupado, color_envase, cantidad_abs, fecha_carga) 
    SELECT DISTINCT centro, sku, texto_breve_material, movimiento, almacen, cantidad, unidad_medida_base, fecha_contabilizacion, fecha_entrada, sag, uen, drv, cupo, tipo_envase, cupo_agrupado, color_envase, cantidad_abs, fecha_carga
    FROM planning.env_seleccion_envase_seleccionado
    WHERE NOT EXISTS (
        SELECT 'X' 
        FROM planning.env_seleccion_envase_seleccionado_temp
        WHERE 
            planning.env_seleccion_envase_seleccionado_temp.fecha_carga = 
            planning.env_seleccion_envase_seleccionado.fecha_carga
    );

我只使用字段 FECHA_CARGA 作为比较,因为这个字段有记录插入的日期,我也尝试使用来自table 在查询的“Where”部分,但它也不起作用。

在这两种情况下,我都得到了 ** INSERT 0 0 ** 的结果,它什么也没插入

你们能帮帮我吗?有任何想法吗?抱歉,如果解决方案很明显,但我有点新

您是从产品 table 插入的,它应该来自临时 table 并检查临时 table:

INSERT INTO planning.env_seleccion_envase_seleccionado(centro, sku, texto_breve_material, movimiento, almacen, cantidad, unidad_medida_base, fecha_contabilizacion, fecha_entrada, sag, uen, drv, cupo, tipo_envase, cupo_agrupado, color_envase, cantidad_abs, fecha_carga) 
SELECT DISTINCT centro, sku, texto_breve_material, movimiento, almacen, cantidad, unidad_medida_base, fecha_contabilizacion, fecha_entrada, sag, uen, drv, cupo, tipo_envase, cupo_agrupado, color_envase, cantidad_abs, fecha_carga
FROM    
    planning.env_seleccion_envase_seleccionado_temp  --<-- here
WHERE
    NOT EXISTS (
        SELECT
            'X'
        FROM
            planning.env_seleccion_envase_seleccionado --<-- here
        WHERE
            planning.env_seleccion_envase_seleccionado_temp.fecha_carga = planning.env_seleccion_envase_seleccionado.fecha_carga
    );

示例:

insert into
  usuario(id, email)
select
  nextval('seq_usuario'),
  'email@gmail.com'
where
  NOT EXISTS (
    select
      id,
      email
    from
      usuario
    where
      email like 'email@gmail.com'
  );