gpt4 book ai didi

sql - 通过选择插入时,如何在插入表之前检查重复项

转载 作者:行者123 更新时间:2023-12-02 10:53:09 25 4
gpt4 key购买 nike

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

insert into table1
select col1, col2
from table2

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

最佳答案

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

替代使用 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

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

关于sql - 通过选择插入时,如何在插入表之前检查重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5599874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com