Computer >> 컴퓨터 >  >> 프로그래밍 >> MySQL

MySQL에서 INSERT 시 MAX()+1 값 넣는 방법 – COALESCE 함수 활용

MySQL에서 특정 조건(그룹)별로 최댓값에 1을 더한 새 ID를 삽입하려면 COALESCE() 함수를 사용하면 됩니다. COALESCE는 여러 인수 중 첫 번째로 NULL이 아닌 값을 반환하는 함수로, 해당 조건의 데이터가 없어 MAX()가 NULL을 반환하는 경우 기본값 0을 대신 사용하도록 처리해 줍니다.

기본 문법

INSERT INTO yourTableName(yourColumnName1, yourColumnName2)
SELECT 1 + COALESCE((SELECT MAX(yourColumnName1) FROM yourTableName WHERE yourColumnName2 = 'yourValue'), 0), 'yourValue';

문법을 제대로 이해하기 위해 실제 예제 테이블을 만들어 단계별로 확인해 보겠습니다.

1. 테이블 생성

mysql> create table InsertMaxPlus1Demo
    -> (
    -> Id int,
    -> Name varchar(20)
    -> );
Query OK, 0 rows affected (1.27 sec)

2. 샘플 데이터 삽입

INSERT 명령으로 몇 개의 레코드를 추가합니다.

mysql> insert into InsertMaxPlus1Demo(Id,Name) values(1,'John');
Query OK, 1 row affected (0.12 sec)
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(1,'Mike');
Query OK, 1 row affected (0.21 sec)
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(2,'John');
Query OK, 1 row affected (0.12 sec)
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(1,'Larry');
Query OK, 1 row affected (0.20 sec)
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(3,'John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into InsertMaxPlus1Demo(Id,Name) values(2,'David');
Query OK, 1 row affected (0.17 sec)

3. 전체 데이터 확인

mysql> select *from InsertMaxPlus1Demo;

실행 결과는 다음과 같습니다.

+------+-------+
| Id   | Name  |
+------+-------+
|    1 | John  |
|    1 | Mike  |
|    2 | John  |
|    1 | Larry |
|    3 | John  |
|    2 | David |
+------+-------+
6 rows in set (0.00 sec)

4. MAX()+1 값 삽입하기

이제 Name이 'John'인 레코드 중 가장 큰 Id에 1을 더한 값을 삽입하는 쿼리입니다.

mysql> INSERT INTO InsertMaxPlus1Demo (Id, Name)
    -> SELECT 1 + coalesce((SELECT max(Id) FROM InsertMaxPlus1Demo WHERE Name='John'), 0), 'John';
Query OK, 1 row affected (0.21 sec)
Records: 1 Duplicates: 0 Warnings: 0

위 쿼리는 이름이 'John'인 레코드를 검사합니다. 현재 John의 최대 Id는 3이므로, 새로 삽입되는 레코드에는 Id 4가 할당됩니다.

5. 결과 확인

mysql> select *from InsertMaxPlus1Demo;

실행 결과는 다음과 같습니다.

+------+-------+
| Id   | Name  |
+------+-------+
|    1 | John  |
|    1 | Mike  |
|    2 | John  |
|    1 | Larry |
|    3 | John  |
|    2 | David |
|    4 | John  |
+------+-------+
7 rows in set (0.00 sec)

이처럼 COALESCE()와 서브쿼리의 MAX()를 조합하면 조건별로 중복되지 않는 순번을 손쉽게 생성해 삽입할 수 있습니다. 다만 여러 세션에서 동시에 삽입이 일어나는 환경이라면 경합 상태가 발생할 수 있으므로, 잠금 처리를 하거나 AUTO_INCREMENT 컬럼 사용을 함께 고려하는 것이 안전합니다.