database

[MySQL, MyBatis] LAST_INSERT_ID()

study-minjeong 2024. 7. 24. 08:52

LAST_INSERT_ID()는 최근에 성공적으로 수행된 insert 구문의 첫번째 auto_increment 컬럼의 값을 반환한다. 또한 세션마다 다른 값을 가지고 있다. 각 세션에서 insert가 실행될 때의 auto_increment로 설정된 컬럼의 시작값이다.

* auto_increment는 새로운 데이터가 입력될 때 자동으로 1씩 증가된 값을 저장하는 속성이다.

 

 

예제 코드

INSERT INTO last_insert_id_table(col)
VALUES('1row'),('2row'),('3row');

-> 이 쿼리가 실행되고 나서의 last_insert_id는 1이다.

INSERT INTO last_insert_id_table(col)
VALUES('1row');

INSERT INTO last_insert_id_table(col)
VALUES('2row');

INSERT INTO last_insert_id_table(col)
VALUES('3row');

-> 이 쿼리가 실행되고 나서의 last_insert_id는 3이다.

 

last_insert_id() 함수는 1개의 insert 쿼리에 대해서 성공 시 마지막 auto_increment값을 제공한다.