MySQL: re-use auto-increment during insert

后端 未结 3 383
-上瘾入骨i
-上瘾入骨i 2021-01-20 05:32

I\'m designing a comments MySQL db, and my comments table has fields:

  • id primary key, auto-incr
  • thread int, not null
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-20 06:18

    Do I have to use 2 queries?

    Yes. As you discovered, the id value hasn't been generated yet in a BEFORE INSERT trigger. But you can't change your NEW.thread value in an AFTER INSERT trigger.

    You can't rely on reading the INFORMATION_SCHEMA, because you can cause a race condition.

    You'll just have to do the INSERT, and then immediately execute:

    UPDATE comments SET thread=id WHERE id=LAST_INSERT_ID() AND thread IS NULL;
    

    If it's a root comment.

    See also my past answers on the similar topic:

    • Concatenating a string and primary key Id while inserting
    • Two autoincrements columns or autoincrement and same value in other column

提交回复
热议问题