You can use something like the following using a INSERT ... SELECT
:
INSERT INTO document_control
SELECT CONCAT_WS('-', RIGHT(YEAR(CURRENT_TIMESTAMP), 2), LPAD(COUNT(*) + 1, 3, 0))
FROM document_control
WHERE LEFT(id_custom, 2) = RIGHT(YEAR(CURRENT_TIMESTAMP), 2)
Note: It can be dangerous to use such a generated custom ID as identifier for specific records since the custom ID can change after changing the data (UPDATE
or DELETE
) of the table. So I don't recommend to use this custom ID as foreign key on other tables.
A better solution (in my opinion) would be the following:
CREATE TABLE document_control (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
name VARCHAR(10)
);
You are using a table with column id
using auto increment (so the database organizes the ID itself) and the created_at
column to store the date and time of the creation. You can use CURRENT_TIMESTAMP
as default value so you don't have to provide a value on INSERT
everytime. With these two columns you can get your custom ID with a simple query:
SELECT *, CONCAT_WS('-', RIGHT(YEAR(created_at), 2), LPAD(id, 3, 0)) AS custom_id
FROM document_control
You can create a VIEW
to generate the custom ID in the background. In this case you don't have to build the custom ID on every SELECT
yourself:
-- create the VIEW
CREATE VIEW v_document_control AS
SELECT *, CONCAT_WS('-', RIGHT(YEAR(created_at), 2), LPAD(id, 3, 0)) AS custom_id
FROM document_control
-- use the VIEW
SELECT * FROM v_document_control
In case you need a consecutive number without gaps and starting on "1" every year, you can use the above example (same columns) but with the following SELECT
using ROW_NUMBER
(since MySQL 8.0):
SELECT *, CONCAT_WS('-', RIGHT(YEAR(created_at), 2), LPAD(ROW_NUMBER() OVER (PARTITION BY YEAR(created_at) ORDER BY id), 3, 0)) AS custom_id
FROM document_control
demo on dbfiddle.uk