简体   繁体   English

SQL Server - 从 tbl1 插入 tbl2,其中 tbl1.column1 <> tbl2.column1

[英]SQL Server - Insert into tbl2 from tbl1 where tbl1.column1 <> tbl2.column1

I have 2 tables, which have the same columns.我有 2 个表,它们具有相同的列。 Like the topic title says, I'd like to insert into the 2nd tables the records of the 1st table where the values of the same column are different.就像主题标题所说的那样,我想将第一个表的记录插入到第二个表中,其中同一列的值不同。

I've tried with:我试过:

SELECT * FROM Table1 INNER JOIN Table2 ON Table2.column1 <> Table1.column1;

or或者

SELECT * FROM Table1, Table2 WHERE Table1.column1 <> Table2.column1;

But the results are replicated values from the two tables, I think because I select from both tables.但是结果是从两个表中复制的值,我想是因为我从两个表中进行了选择。

If I do the following:如果我执行以下操作:

INSERT INTO Table2 SELECT * FROM Table1 WHERE Table1.column1 <> Table2.column1;

it throws me an error of:它给我一个错误:

Impossibile associare l'identificatore in più parti "Table2.column1"在 più parti "Table2.column1" 中不可能有关联

You cannot compare column values unless you specify which row you are talking about.除非您指定要讨论的行,否则您无法比较列值。 In your case, it sounds like the answer to the question "which row" is "any row in Table2 ", so you can apply the existential quantifier to rows of Table2 to decide which rows of Table1 you wish to insert.在您的情况下,这听起来像是“哪一行”是“ Table2任何行”问题的答案,因此您可以将存在量词应用于Table2行来决定要插入Table1哪些行。 Long story short, you tell SQL to insert the missing rows.长话短说,您告诉 SQL 插入丢失的行。

The corresponding SQL is as follows:对应的SQL如下:

INSERT INTO Table2
    SELECT * FROM Table1 t1
    WHERE NOT EXISTS (
        SELECT * FROM Table2 t2
        WHERE t1.column1 = t2.column1
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM