I\'m designing a comments MySQL db, and my comments table has fields:
id
primary key, auto-incrthread
int, not null
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