Skip to content

Instantly share code, notes, and snippets.

@wataru420
Created August 23, 2012 06:31
Show Gist options
  • Save wataru420/3433396 to your computer and use it in GitHub Desktop.
Save wataru420/3433396 to your computer and use it in GitHub Desktop.
MySQLのTRIGGERとLAST_INSERT_IDについて
USE last_insert_test;
CREATE TABLE table1 (
id1 int
) ENGINE=InnoDB;
CREATE TABLE table2 (
id2 int
) ENGINE=InnoDB;
INSERT INTO table2 VALUES(NULL);
INSERT INTO table1 VALUES (NULL);
SELECT LAST_INSERT_ID();
delimiter //
CREATE TRIGGER table1_before_insert BEFORE INSERT ON table1 FOR EACH ROW
BEGIN
DECLARE last_id1 INT;
IF NEW.id1 IS NULL THEN
BEGIN
SELECT MAX(id1) INTO last_id1 FROM table1;
IF last_id1 IS NULL THEN
SET NEW.id1 = 101;
ELSE
SET NEW.id1 = last_id1 + 5;
END IF;
UPDATE table2 SET id2=LAST_INSERT_ID(NEW.id1);
END;
END IF;
END;//
delimiter ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment