I\'m designing a comments MySQL db, and my comments table has fields:
id
primary key, auto-incrthread
int, not nullThanks 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
You can simply set thread
to NULL
to signify that the comment is a root comment rather than attached to a thread.
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: