Get last inserted id in trigger?

I am using a trigger to insert a row and want to use the last identifier I created for use in a subsequent request.

How can i do this?

The code looks like this:

BEGIN
IF (NEW.counter >= 100) THEN
INSERT INTO tagCategories (name, counter) VALUES ('unnamed', NEW.counter);
// here i want to have access to the above inserted id
UPDATE tagCategories2tagPairs SET tagCategoryId = <<ID_HERE>> WHERE tagPairId = OLD.id
END IF;
END
+5
source share
5 answers

Have you looked at LAST_INSERT_ID () ? But keep in mind:

If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID () returns the value generated for the first inserted row only.

+7
source

"AAA" ,

DELIMITER //
CREATE TRIGGER company_run_before_insert BEFORE INSERT ON ap_company 
FOR EACH ROW
BEGIN

SET @lastID = (SELECT id FROM ap_company ORDER BY id DESC LIMIT 1);
IF @lastID IS NULL OR @lastID = '' THEN
    SET @lastID = 0;
END IF;
SET @lastID = @lastID +1;
SET NEW.ap_company_id = concat(NEW.company_initials,'-', @lastID);
END;
+1

NEW.id

BEGIN
insert INTO test_questions (test_id, question, variant1, variant2, variant3, w1, type_id) 
SELECT NEW.id, t1.question, t1.v1, t1.v2, t1.v3, t1.answer, 1
FROM new_minitest_questions t1
WHERE t1.mt_id = NEW.old_id;
END
0

Auto Increment . .

For instances, if the column name is “Name” and the column has a value, such as “Robin Shankar,” the trigger will replace the “-” spaces and also add an auto-increment identifier to the end of the bullet, thereby creating a unique slug.

robin_shankar_9071

DELIMITER //
CREATE TRIGGER insert_slug_sd
BEFORE INSERT ON `your_table_name`
FOR EACH ROW
BEGIN

DECLARE auto_increment_ INT(11);

SELECT 
    `auto_increment` 
INTO 
    auto_increment_
FROM INFORMATION_SCHEMA.TABLES
    WHERE 
table_name = 'your_table_name';

SET NEW.`Slug` = CONCAT(LOWER(REPLACE(NEW.`Name`,' ','-')),'-',auto_increment_);
END; //

DELIMITER;
0
source
SET NEW.num=CONCAT("-", (
  SELECT `auto_increment` 
  FROM INFORMATION_SCHEMA.TABLES    
  WHERE table_name = 'menu')
)
0
source

All Articles