INSERT INTO SELECT 如果在 oracle 中不存在

INSERT INTO SELECT if NOT EXISTS in oracle

我有以下查询。我喜欢仅在 TABLE1 中不存在该行时才插入。我该怎么做?

INSERT INTO TABLE1 (VEH_YEAR, VEH_MAKE, ACV_VOLUME)
SELECT VEH_YEAR, VEH_MAKE,
(SELECT COUNT(*)
FROM ACV_VEHICLE_DETAILS
WHERE YEAR     = table2 .veh_year
AND MAKE       = table2 .veh_make
) AS ACV_VOLUME
FROM TABLE2 table2 WHERE VEH_YEAR IS NOT NULL AND VEH_MAKE IS NOT NULL;

使用not exists:

INSERT INTO TABLE1 (VEH_YEAR, VEH_MAKE, ACV_VOLUME)
    SELECT VEH_YEAR, VEH_MAKE, 
           (SELECT COUNT(*)
            FROM ACV_VEHICLE_DETAILS vd
            WHERE vd.YEAR = t2.veh_year AND vd.MAKE = t2.veh_make
           ) AS ACV_VOLUME
    FROM TABLE2 t2 
    WHERE VEH_YEAR IS NOT NULL AND VEH_MAKE IS NOT NULL AND
          NOT EXISTS (SELECT 1
                      FROM table1 t1
                      WHERE t1.veh_year = t2.veh_year and t1.veh_make = t2.veh_make
                     );

您可以这样使用 NOT EXISTS

INSERT  INTO TABLE1 ( VEH_YEAR, VEH_MAKE, ACV_VOLUME)
SELECT  VEH_YEAR
      , VEH_MAKE
      , ( SELECT    COUNT(*)
          FROM      ACV_VEHICLE_DETAILS
          WHERE     YEAR = t2.veh_year
                AND MAKE = t2.veh_make
         ) AS ACV_VOLUME
FROM    TABLE2 t2
WHERE   VEH_YEAR IS NOT NULL
    AND VEH_MAKE IS NOT NULL
    AND NOT EXISTS (SELECT 1
                    FROM  Table1 t1 
                    WHERE t1.VEH_YEAR = t2.VEH_YEAR
                      AND t1.VEH_MAKE = t2.VEH_MAKE
                      );

假设您只想在 VEH_MAKEVEH_YEAR 都已存在时排除,如果您想从 INSERT 中排除所有基于 VEH_MAKE 的记录一个人你只是改变相关的 WHERE 标准,排除 t1.VEH_YEAR = t2.VEH_YEAR

经典LEFT JOIN:

INSERT INTO TABLE1 (VEH_YEAR, VEH_MAKE, ACV_VOLUME)
SELECT VEH_YEAR, VEH_MAKE, ACV_VOLUME 
FROM(SELECT VEH_YEAR, VEH_MAKE,
            (SELECT COUNT(*)
            FROM ACV_VEHICLE_DETAILS
            WHERE YEAR = table2.veh_year
            AND MAKE = table2.veh_make) AS ACV_VOLUME
     FROM TABLE2 table2 WHERE VEH_YEAR IS NOT NULL AND VEH_MAKE IS NOT NULL
    )t
LEFT JOIN TABLE1 t1 on t.VEH_YEAR = t1.VEH_YEAR AND t.VEH_MAKE = t1.VEH_MAKE AND t.ACV_VOLUME = t1.ACV_VOLUME
WHERE t1.VEH_YEAR IS NULL

您可以将 MERGEWHEN NOT MATCHED THEN INSERT 一起使用:

merge into Table1 t
using (
   SELECT VEH_YEAR, VEH_MAKE,
   (SELECT COUNT(*)
    FROM ACV_VEHICLE_DETAILS
    WHERE YEAR     = table2 .veh_year
    AND MAKE       = table2 .veh_make
   ) AS ACV_VOLUME
   FROM TABLE2 table2 WHERE VEH_YEAR IS NOT NULL AND VEH_MAKE IS NOT NULL
) d
on (t.veh_year = d.veh_year and t.veh_make = d.veh_make)
when not matched then insert (veh_year, veh_make, acv_volume)
                      values (d.veh_year, d.veh_make, d.acv_volume);

别忘了提交 :)