【问题标题】:Insert new data in the table without deleting existing data在表中插入新数据而不删除现有数据
【发布时间】:2021-03-20 23:55:26
【问题描述】:

我有一个超过三百万条记录的表,每一个都有一个唯一的字段c_document,我需要用一个相等的字段更新表,但是新表有新的记录,我不能删除已经存在的记录。 实际上,这张表每三个月他们就会向我传递这个带有新记录的更新表,我只需要在我的数据库中添加新的表。 有没有办法如果不存在插入,如果不存在则不插入但立即执行? sql文件为500MB。

感谢您的帮助

TABLE

c_id
c_laname
c_mname
c_fname
c_document
c_email
c_dob

【问题讨论】:

    标签: mysql sql duplicates sql-insert


    【解决方案1】:

    您可以使用on duplicate key。首先,您需要在列c_document 上设置唯一约束(或主键约束)。

    然后,您可以像这样从source_table 插入到target_table

    insert into target_table (c_id, c_lname, c_mname, c_fname, c_document, c_email, c_dob)
    select c_id, c_lname, c_mname, c_fname, c_document, c_email, c_dob
    from source_table
    on duplicate key update c_document = values(c_document)
    

    update 子句基本上是空操作:我们已经知道c_document 在源行和目标行上是相同的,因为这就是冲突的定义。

    您也可以使用insert ignore - 但我不是这种语法的忠实拥护者,因为它基本上会忽略所有错误,而不仅仅是与重复键相关的错误:

    insert ignore into target_table (c_id, c_lname, c_mname, c_fname, c_document, c_email, c_dob)
    select c_id, c_lname, c_mname, c_fname, c_document, c_email, c_dob
    from source_table
    

    【讨论】:

      【解决方案2】:

      插入不存在行的另一个选项

      insert into target table (c_id, c_lname, c_mname, c_fname, c_document, c_email, c_dob)
      select (c_id, c_lname, c_mname, c_fname, c_document, c_email, c_dob) 
      from source_table s
      where not exists
          (select 1 from target_table t where t.c_document=s.c_document);
      

      不确定它如何处理数百万行。

      【讨论】:

        猜你喜欢
        • 2020-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-26
        • 1970-01-01
        • 2019-09-09
        • 2020-07-13
        • 1970-01-01
        相关资源
        最近更新 更多