MySQL에서는 INSERT 문에 SELECT 쿼리를 결합하여 데이터를 삽입할 수 있습니다. 이 방식은 값을 직접 입력하는 것뿐만 아니라, 다른 테이블의 데이터를 조회해서 삽입하는 등 다양한 상황에서 유용하게 활용됩니다.
기본 문법
SELECT 쿼리와 함께 INSERT를 수행하려면 아래와 같은 문법을 사용합니다.
insert into yourTableName(yourColumnName1,yourColumnName2,yourColumnName3,...N)
select yourValue1,yourValue2,yourValue3,......N;
예제 테이블 생성
먼저 실습에 사용할 테이블을 생성해 보겠습니다.
mysql> create table DemoTable1603
-> (
-> StudentId int,
-> StudentName varchar(20),
-> StudentMarks int
-> );
Query OK, 0 rows affected (0.50 sec)
INSERT ... SELECT로 데이터 삽입
이제 insert 명령을 사용해 테이블에 레코드를 삽입합니다. VALUES 절 대신 select 절에 삽입할 값들을 나열하면 됩니다.
mysql> insert into DemoTable1603(StudentId,StudentName,StudentMarks) select 101,'John',45;
Query OK, 1 row affected (0.17 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> insert into DemoTable1603(StudentId,StudentName,StudentMarks) select 102,'Adam',76;
Query OK, 1 row affected (0.11 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> insert into DemoTable1603(StudentId,StudentName,StudentMarks) select 103,'Bob',67;
Query OK, 1 row affected (0.31 sec)
Records: 1 Duplicates: 0 Warnings: 0
삽입 결과 확인
select 문을 사용하여 테이블의 모든 레코드를 조회합니다.
mysql> select * from DemoTable1603;
실행 결과는 다음과 같습니다.
+-----------+-------------+--------------+
| StudentId | StudentName | StudentMarks |
+-----------+-------------+--------------+
| 101 | John | 45 |
| 102 | Adam | 76 |
| 103 | Bob | 67 |
+-----------+-------------+--------------+
3 rows in set (0.00 sec)
정리
INSERT ... SELECT 구문은 VALUES 절 대신 SELECT 쿼리의 결과를 그대로 테이블에 삽입할 수 있게 해주는 기능입니다. 특히 다른 테이블에서 조건에 맞는 데이터를 추출해 새 테이블에 저장하거나, 대량의 데이터를 복사할 때 매우 효율적으로 활용할 수 있습니다.