Computer >> 컴퓨터 >  >> 프로그램 작성 >> MySQL

MySQL INSERT MAX()+1을 구현하시겠습니까?

<시간/>

이를 위해 COALESCE() 함수를 사용해야 합니다. 구문은 다음과 같습니다.

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

위의 구문을 이해하기 위해 테이블을 생성해 보겠습니다. 테이블 생성 쿼리는 다음과 같습니다.

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

이제 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)

select 문을 사용하여 테이블의 모든 레코드를 표시합니다. 쿼리는 다음과 같습니다.

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)

다음은 MAX()+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을 확인하고 있습니다. ID가 3이고 레코드가 ID 4로 삽입됩니다.

이제 select 문을 사용하여 테이블 레코드를 다시 한 번 확인하십시오. 쿼리는 다음과 같습니다.

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)