Answer the question
In order to leave comments, you need to log in
Mysql how to make an alternate numbering field?
I have a table with the following structure:
CREATE TABLE `items` (
`id` int AUTO_INCREMENT ,
`category_id` int,
PRIMARY KEY (`id`)
);
id category_id
1 1
2 1
3 1
4 2
5 3
6 2
7 3
8 2
9 3
id category_id alt_id
1 1 1
2 1 2
3 1 3
4 2 1
5 3 1
6 2 2
7 3 2
8 2 3
9 3 3
Answer the question
In order to leave comments, you need to log in
hang trigger
DELIMITER $$
CREATE TRIGGER `items_BEFORE_INSERT` BEFORE INSERT ON `items` FOR EACH ROW
BEGIN
DECLARE oldmax INT;
SELECT IFNULL(MAX(`alt_id`), 0)
FROM `items`
WHERE `category_id` = NEW.`category_id`
INTO oldmax;
SET NEW.`alt_id` = oldmax+1;
END$$
DELIMITER ;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question