doulu1544 2013-09-20 13:31
浏览 225
已采纳

SQL拒绝批量插入,因为单行是重复的

I don't know the proper term, but by "Batch insert" what I mean is..

INSERT INTO `table` (`column1`, `column2`, `column3`) VALUES 
("value1", "value2", "value3"),
("value4", "value5", "value6"),
("value7", "value8", "value9")

We're inserting multiple rows in a single query to save resources.

We have a composite key set up on this table to avoid getting duplicate records. Problem is, when there is a duplicate record, it rejects the entire "batch", so in the example above, if "value1" already existed in the column1 column, it will not insert any of the 3 rows.

We are using PHP with the mysql_ functions (yes, I know they're being deprecated, let's address one problem at a time please)

So my question is, is there a way to insert multiple rows at once where, in the event of a duplicate row, it will still insert the rest of the rows in the "batch"?

Thanks for your help.

  • 写回答

2条回答 默认 最新

  • douhanzhen8927 2013-09-20 13:33
    关注

    Try the ignore keyword

    INSERT IGNORE INTO `table` ...
    

    If you use the IGNORE keyword, errors that occur while executing the INSERT statement are ignored. 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. With IGNORE, the row still is not inserted, but no error occurs. Ignored errors may generate warnings instead, although duplicate-key errors do not.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试