douningle7944 2018-09-27 11:19
浏览 75

使用ON DUPLICATE UPDATE时,PDO可以避免间隙[重复]

This question already has an answer here:

I'm using pdo to handle my database and I've just noticed that when I try to insert multiple rows if I use ON DUPLICATE KEY UPDATE there is a gap in the auto-incremented field(in my case it is called id).

This is my table:

id  |  name  |  age 
1   |  Emma  |  20
2   |  Jane  |  21
3   |  John  |  25

And my statement is:

$pdo->prepare('
    INSERT INTO person 
        (`name`, `age`) 
    VALUES 
        (?, ?), (?, ?), (?, ?)
    ON DUPLICATE KEY UPDATE 
        age = VALUES(`age`)
')->execute(['Emma', '20', 'Jane', '21', 'Sarah', '35']);

If i run this query it will insert name: Sarah, age: 35 with id 6(a gap of 2 ids). Why is this happening? And is there a solution to that?

(p.s i want it to work with multiple rows insert)

</div>
  • 写回答

1条回答 默认 最新

  • dongtiao2066 2018-09-27 11:31
    关注

    That's expected behaviour for auto_increment values. It increments the value every time you run anINSERT on it. Even if that insert fails because of a unique value already existing. So even though you have a ON DUPLICATE KEY value in your query, it still tries to INSERT them once before realising they are already in there.

    If you want to work around this you could split your query into two parts where you first try to SELECT the users and then when you see they don't exist, you INSERT them. That way you don't try to INSERT any values that might already exist so you won't increment the auto_increment value.

    EDIT: You can also play around with the auto increment lock mode. I'm not exactly sure how reliable this is, but you can find some information on it here: https://dev.mysql.com/doc/refman/8.0/en/innodb-auto-increment-handling.html

    评论

报告相同问题?

悬赏问题

  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败