MySQL: re-use auto-increment during insert

后端 未结 3 385
-上瘾入骨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条回答
  •  梦毁少年i
    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

提交回复
热议问题