MySQL: re-use auto-increment during insert

后端 未结 3 384
-上瘾入骨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 05:56

    Thanks to Michael's answer I started looking into triggers; basically event-handlers that run some code when something happens. Michael's trigger didn't work for me, but the following does:

    USE `my_db_name`;
    DELIMITER $$
    CREATE TRIGGER comments_bi 
    BEFORE INSERT ON `comments`
    FOR EACH ROW
    BEGIN
      DECLARE nextID INT DEFAULT 0;
    
      SELECT AUTO_INCREMENT INTO nextID FROM information_schema.tables
      WHERE table_name = 'comments' AND table_schema = DATABASE();
    
      IF NEW.`thread` IS NULL OR NEW.`thread` = 0 THEN
        SET NEW.`thread` = nextID;
      END IF;
    
    END $$
    DELIMITER ;
    

    One big caveat: because this trigger requires access to the information_schema, only the root account could define it.

    Thanks to this answer for inspiration

    0 讨论(0)
  • 2021-01-20 06:15

    You can simply set thread to NULL to signify that the comment is a root comment rather than attached to a thread.

    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题