Created
August 23, 2012 06:31
-
-
Save wataru420/3433396 to your computer and use it in GitHub Desktop.
MySQLのTRIGGERとLAST_INSERT_IDについて
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
USE last_insert_test; | |
CREATE TABLE table1 ( | |
id1 int | |
) ENGINE=InnoDB; | |
CREATE TABLE table2 ( | |
id2 int | |
) ENGINE=InnoDB; | |
INSERT INTO table2 VALUES(NULL); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
INSERT INTO table1 VALUES (NULL); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT LAST_INSERT_ID(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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