如何通过select插入表插入表之前,如何检查重复项

时间:2022-02-15 07:37:50

How can I check for duplicates before inserting into a table when inserting by select:

如何通过选择插入时插入表格之前如何检查重复项:

insert into table1
select col1, col2 
from table2

I need to check if table1 already has a row with table1.col1.value = table2.col1.value, and if yes, then exclude that row from the insert.

我需要检查table1是否已经有一行table1.col1.value = table2.col1.value,如果是,则从插入中排除该行。

4 个解决方案

#1


15  

INSERT INTO table1 
SELECT t2.col1, 
       t2.col2 
FROM   table2 t2 
       LEFT JOIN table1 t1 
         ON t2.col1 = t1.col1 
            AND t2.col2 = t1.col2 
WHERE  t1.col1 IS NULL 

Alternative using except

替代使用除外

INSERT INTO @table2 
SELECT col1, 
       col2 
FROM   table1 
EXCEPT 
SELECT t1.col1, 
       t1.col2 
FROM   table1 t1 
       INNER JOIN table2 t2 
         ON t1.col1 = t2.col1 
            AND t1.col2 = t2.col2 

Alternative using Not Exists

替代使用不存在

INSERT INTO table2 
SELECT col1,col2 
FROM table1 t1
WHERE
NOT EXISTS( SELECT 1
    FROM table2 t2
    WHERE t1.col1 = t2.col1
          AND t1.col2 = t2.col2)

#2


1  

insert into table1
select col1, col2 
from table2 
where table2.col1 not in (select col1 from table1)

#3


-1  

insert into table1
select distinct col1, col2 
from table2 

#4


-1  

You can simply add IGNORE into your insert statement.

您只需将IGNORE添加到insert语句中即可。

e.g

例如

INSERT IGNORE INTO table1
SELECT col1, col2 
FROM table2

This is discussed here

这在这里讨论

#1


15  

INSERT INTO table1 
SELECT t2.col1, 
       t2.col2 
FROM   table2 t2 
       LEFT JOIN table1 t1 
         ON t2.col1 = t1.col1 
            AND t2.col2 = t1.col2 
WHERE  t1.col1 IS NULL 

Alternative using except

替代使用除外

INSERT INTO @table2 
SELECT col1, 
       col2 
FROM   table1 
EXCEPT 
SELECT t1.col1, 
       t1.col2 
FROM   table1 t1 
       INNER JOIN table2 t2 
         ON t1.col1 = t2.col1 
            AND t1.col2 = t2.col2 

Alternative using Not Exists

替代使用不存在

INSERT INTO table2 
SELECT col1,col2 
FROM table1 t1
WHERE
NOT EXISTS( SELECT 1
    FROM table2 t2
    WHERE t1.col1 = t2.col1
          AND t1.col2 = t2.col2)

#2


1  

insert into table1
select col1, col2 
from table2 
where table2.col1 not in (select col1 from table1)

#3


-1  

insert into table1
select distinct col1, col2 
from table2 

#4


-1  

You can simply add IGNORE into your insert statement.

您只需将IGNORE添加到insert语句中即可。

e.g

例如

INSERT IGNORE INTO table1
SELECT col1, col2 
FROM table2

This is discussed here

这在这里讨论