목차

MySQL INSERT_SELECT_Statement

  • description : MySQL INSERT_SELECT_Statement
  • author : 오션
  • email : shlim@repia.com
  • lastupdate : 2022-11-30 Wed


MySQL 5.6 Reference Manual


INSERT Statement


INSERT ...SELECT Statement

The target table of the INSERT statement may appear in the FROM clause of the SELECT part of the query.
However, you cannot insert into a table and select from the same table in a subquery.

INSERT 구분의 타겟 테이블은 쿼리의 SELECT 부분의 FROM 절에서 나타날수도 있습니다.
그러나, 서브쿼리에서는 동일한 테이블에서 SELECT하여 INSERT할 수 없습니다.

To avoid ambiguous column reference problems when the SELECT and the INSERT refer to the same table,
provide a unique alias for each table used in the SELECT part, and qualify column names in that part with the appropriate alias.

SELECT와 INSERT가 동일한 테이블을 참조할 때, 모호한 컬럼 참조 문제를 방지하기 위해,
SELECT 부분에서 사용되는 각 테이블에 대한 유일한 에일리어스(alias, 별칭)를 제공하고, 해당 에일리어스로 컬럼 이름을 한정하세요.

<수정 전> 오류 발생(java.sql.exception:Invalid use of group function)

INSERT INTO CHECKLIST (CHECKLIST_ORDER, CHECKLIST_TITLE, CHECKLIST_ITEMS)
VALUES (
    (SELECT MAX(CHECKLIST_ORDER) FROM CHECKLIST) + 1
    , '[Test] 홍길동 프로젝트'
    , '#탐라국'
);
<!-- INSERT구문 실행 시, CHECKLIST 테이블에서 CHECKLIST_ORDER의 최대값을 SELECT한 후 그 값에 1을 더한 값을 CHECKLIST_ORDER 컬럼에 삽입 -->
<!-- 테이블 명에 유의!!! -->


<수정 후>

INSERT INTO CHECKLIST (CHECKLIST_ORDER, CHECKLIST_TITLE, CHECKLIST_ITEMS)
VALUES (
    (SELECT MAX(C.CHECKLIST_ORDER) FROM CHECKLIST C) + 1
    , '[Test] 홍길동 프로젝트'
    , '#탐라국'
);
<!-- INSERT구문 실행 시, CHECKLIST 테이블에서 CHECKLIST_ORDER의 최대값을 SELECT한 후 그 값에 1을 더한 값을 CHECKLIST_ORDER 컬럼에 삽입 -->
<!-- 테이블 명에 유의!!! -->

13.2.5.1 INSERT...SELECT Statement
[MYSQL] INSERT MAX + 1