When I insert a new row, an auto increment ID will be saved like 1,2,3.. I need to custom it using a Trigger so it will be saved like 20171,20172,20173..
-
Seems odd, but ok. What do you want to 10th value in that series to be, 201710?Alden W.– Alden W.2017-05-30 23:45:58 +00:00Commented May 30, 2017 at 23:45
-
Thank you for the comment. it's ok to be 2017257 :)Mohammed Aladham– Mohammed Aladham2017-05-30 23:47:24 +00:00Commented May 30, 2017 at 23:47
-
I want to make it like 2017+the_old_idMohammed Aladham– Mohammed Aladham2017-05-30 23:48:57 +00:00Commented May 30, 2017 at 23:48
-
Ok, gotcha. And now you may have a reason for needing that. I was just hoping to point out that the order of the index won't be grouped by years unless you use characters. Which you could do.Alden W.– Alden W.2017-05-30 23:49:41 +00:00Commented May 30, 2017 at 23:49
-
Maybe I didn't get it, but I believe that can be done using a Trigger, right?Mohammed Aladham– Mohammed Aladham2017-05-30 23:53:12 +00:00Commented May 30, 2017 at 23:53
|
Show 2 more comments
1 Answer
This trigger would do this.
CREATE DEFINER=`root`@`%` TRIGGER `test_before_insert` BEFORE INSERT ON `test` FOR EACH ROW BEGIN
SET NEW.id = (
SELECT CONCAT(YEAR(CURDATE()),IFNULL(MAX(CAST(ids.id AS UNSIGNED))+1,1))
FROM (
SELECT RIGHT(t.id,LENGTH(t.id)-4) AS id
FROM test t
WHERE LEFT(t.id,4) = YEAR(CURDATE())
) ids
);
END
But there are many reason you would not want to. This will get exponentially more expensive as rows are inserted, and provides no viable sorting etc.
1 Comment
Mohammed Aladham
Thanks very much, I will test it as soon as possible when I reach office