0

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..

7
  • Seems odd, but ok. What do you want to 10th value in that series to be, 201710? Commented May 30, 2017 at 23:45
  • Thank you for the comment. it's ok to be 2017257 :) Commented May 30, 2017 at 23:47
  • I want to make it like 2017+the_old_id Commented 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. Commented May 30, 2017 at 23:49
  • Maybe I didn't get it, but I believe that can be done using a Trigger, right? Commented May 30, 2017 at 23:53

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much, I will test it as soon as possible when I reach office

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.