如果没有在oracle中存在,则INSERT INTO SELECT

时间:2015-05-07 19:18:53

标签: sql oracle not-exists

我有以下查询。我只想在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;

4 个答案:

答案 0 :(得分:0)

使用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
                     );

答案 1 :(得分:0)

您可以像这样使用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

答案 2 :(得分:0)

经典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

答案 3 :(得分:0)

您可以将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);

别忘了承诺:)