Answer the question
In order to leave comments, you need to log in
How to affect last_insert_id() from trigger (MySQL/MariaDB)?
There is a table like this (InnoDB is required):
CREATE TABLE `tbl` (
`id1` int(11) NOT NULL AUTO_INCREMENT,
`id2` int(11) NOT NULL,
PRIMARY KEY (`id1`,`id2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE DEFINER=`root`@`localhost` TRIGGER `db`.`tbl_BEFORE_INSERT` BEFORE INSERT ON `tbl` FOR EACH ROW BEGIN
SET NEW.id1 = (SELECT COALESCE(MAX(id1) + 1, 1) FROM `tbl` WHERE id2 = NEW.id2);
END
SET @id = NULL;
SELECT COALESCE(MAX(id1) + 1, 1) INTO @id FROM `tbl` WHERE id2 = NEW.id2;
ALTER TABLE `tbl` AUTO_INCREMENT = @id;
Answer the question
In order to leave comments, you need to log in
Let's start with the fact that AUTO_INCREMENT works after insertion, so you need to change it AFTER INSERT. In passing, I note that in AFTER UPDATE it is impossible to change the field value.
Further, an update in AFTER INSERT is also prohibited .
In total , practically the only solution in this case will be a storage that will change the necessary columns, wrapped in a transaction, for the "atomicity" of the operation.
But the main question is, why the hell do you set AUTO_INCREMENT if you yourself know better than the server what value the newly inserted record should have?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question