A
A
Anton B2018-11-16 14:56:41
MariaDB
Anton B, 2018-11-16 14:56:41

How to use auto_increment field value in MariaDB 10.1 in insert trigger?

Hi everybody!
Task : when adding a new line, it is necessary that the specified field is automatically filled with the value from the auto_increment field.

CREATE TABLE `users` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(20) DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `name` (`name`)
)

Trigger should be like this
CREATE TRIGGER `name_default` BEFORE INSERT ON `users`
FOR EACH ROW IF ISNULL(NEW.name) THEN
    SET NEW.name = CONCAT('Player', NEW.id);    
END IF

But:
- in before insert NEW.id is not yet known;
- in after insert it is impossible to make changes to a new line;
- LAST_INSERT_ID() always returns 0;
- getting LAST_INSERT_ID from the information schema does nothing;
All comments on the Internet on this topic are from 2007-2014.
Suddenly now there is a way to solve my problem.
Thanks for answers!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question