zoukankan      html  css  js  c++  java
  • Using INSERT IGNORE with MySQL to prevent duplicate key errors

    An error will occur when inserting a new record in MySQL if the primary key specified in the insert query already exists. Using the "IGNORE" keyword prevents errors from occuring and other queries are still able to be run.

    Why?

    Although you shouldn't normally attempt to insert a record without first checking if the primary key you want to use has already been used, there may be times when this is required, such as when multiple developers need to update their own copies of a database, and a particular record may already exist in one or other of the databases.

    Inserting a single record

    The syntax is simple - just add "IGNORE" after "INSERT" like so:

    INSERT IGNORE INTO mytable
        (primaryKey, field1, field2)
    VALUES
        ('abc', 1, 2);

    Inserting multiple records

    When inserting mutiple records at once, any that cannot be inserting will not be, but any that can will be:

    INSERT IGNORE INTO mytable
        (primaryKey, field1, field2)
    VALUES
        ('abc', 1, 2),
        ('def', 3, 4),
        ('ghi', 5, 6);

    In the second example above, if records already existed for 'abc' and 'def' then those two records would not be inserted, but the record for 'ghi' would be.

    https://www.electrictoolbox.com/mysql-insert-ignore/

  • 相关阅读:
    说文解字 —— 拆字
    4K 对齐与固态硬盘检测工具
    硬盘分区(主分区、扩展分区、逻辑分区)
    python+caffe训练自己的图片数据流程
    亲和数(220/284)
    浅谈多进程多线程的选择
    Linux下的多线程编程
    LINUX-进程的概念
    Linux终端那件事儿
    Linux的终端类型
  • 原文地址:https://www.cnblogs.com/softidea/p/6855036.html
Copyright © 2011-2022 走看看