简体   繁体   English

SQL:仅基于主键列将缺失的行从一个表复制到另一个表

[英]SQL: Copy missing rows from one table to another based on primary key column only

I am trying to copy missing rows from one table to another but only if the primary key field does not exist. 我试图将丢失的行从一个表复制到另一个表,但仅限于主键字段不存在时。 Both tables have identical column names but I don't have the number of columns and their names and don't have the primary key column name so it could be "ID" or anything else. 两个表都具有相同的列名,但我没有列数及其名称,并且没有主键列名称,因此它可能是“ID”或其他任何内容。 Let me explain with an example: 让我用一个例子来解释一下:

Table 1: 表格1:

   column 1 (primary key) , Column 2 , Column 3 , ...
   1 , England , London , ...
   2 , France , Paris , ...
   3, Italy , Rome , ...
   4 , Germany , Berlin , ...

Table 2: 表2:

    column 1 (primary key) , Column 2 , Column 3 , ...
    1 , Whatever , Whatever , ...
    2 , Whatever , Whatever , ...

I want to copy row 3 and 4 into table 2 so the outcome will be: 我想将第3行和第4行复制到表2中,结果将是:

Table 2: 表2:

    column 1 (primary key) , Column 2 , Column 3 , ...
    1 , Whatever , Whatever , ...
    2 , Whatever , Whatever , ...
    3 , Italy , Rome , ...
    4 , Germany , Berlin , ...

I have tried 我努力了

   REPLACE INTO table1 SELECT * FROM table2; 

but this will replace the entire table ie Table 2 become exactly like Table 1 但这将取代整个表格,即表2与表1完全相同

You can use insert . . . select 你可以使用insert . . . select insert . . . select insert . . . select : insert . . . select

insert into table2 ( col1, col2 . . . )
    select t1.col1, t1.col2, t1.col3, . . .
    from table1 t1
    where not exists (select 1 from table2 t2 where t2.id = t1.id)

If you just want to ignore rows from table1 with existing primary key in table2 then simplest way is to use INSERT IGNORE syntax: 如果您只想忽略table1包含table2现有主键的行,那么最简单的方法是使用INSERT IGNORE语法:

INSERT IGNORE INTO table2 SELECT * FROM table1;

Note that a row is ignored and not inserted, if there is a duplicate in any UNIQUE KEY (not only PRIMARY). 请注意,如果任何UNIQUE KEY(不仅是PRIMARY)中存在重复,则忽略行而不插入行。

Documentation: INSERT Syntax 文档: INSERT语法

If you use the IGNORE modifier, errors that occur while executing the INSERT statement are ignored. 如果使用IGNORE修饰符,则会忽略执行INSERT语句时发生的错误。 For example, without IGNORE , a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. 例如,如果没有IGNORE ,则复制表中现有UNIQUE索引或PRIMARY KEY值的行会导致重复键错误,并且语句将中止。 With IGNORE , the row is discarded and no error occurs. 使用IGNORE ,该行将被丢弃并且不会发生错误。 Ignored errors generate warnings instead. 忽略的错误会生成警告。

Also note that the columns in both tables should be defined in the same order. 另请注意,两个表中的列应按相同顺序定义。 Actually the tables should have the exactly same schema (same columns with the same data types, length, character sets and collations). 实际上,表应该具有完全相同的模式(具有相同数据类型,长度,字符集和排序规则的相同列)。

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

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