MySQL 쿼리 결과를 CSV 형식으로 화면에 출력하기
MySQL에서 쿼리 결과를 파일로 내보내지 않고 화면에 곧바로 CSV(Comma Separated Value) 형식으로 표시하고 싶다면 concat() 함수를 사용하면 됩니다. 각 컬럼 값을 쉼표(,)로 연결해 하나의 문자열로 만드는 방식입니다.
기본 구문
mysql> select concat(StudentId,',',StudentName,',',StudentAge) as CSVFormat from CSVFormatOutputs;
구문이 어떻게 동작하는지 이해하기 위해 실제 예제 테이블을 만들어 보겠습니다.
1. 테이블 생성
먼저 학생 정보를 저장할 테이블을 생성합니다.
mysql> create table CSVFormatOutputs
-> (
-> StudentId int not null auto_increment,
-> StudentName varchar(20),
-> StudentAge int,
-> PRIMARY KEY(StudentId)
-> );
Query OK, 0 rows affected (1.15 sec)2. 샘플 데이터 입력
insert 명령어를 사용해 몇 개의 레코드를 추가합니다.
mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('Mike',23);
Query OK, 1 row affected (0.26 sec)
mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('John',26);
Query OK, 1 row affected (0.19 sec)
mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('Sam',19);
Query OK, 1 row affected (0.20 sec)
mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('Carol',27);
Query OK, 1 row affected (0.59 sec)
mysql> insert into CSVFormatOutputs(StudentName,StudentAge) values('Bob',24);
Query OK, 1 row affected (0.15 sec)3. 전체 레코드 확인
select 문으로 테이블에 저장된 모든 레코드를 조회해 보겠습니다.
mysql> select *from CSVFormatOutputs;
실행 결과는 다음과 같습니다.
+-----------+-------------+------------+ | StudentId | StudentName | StudentAge | +-----------+-------------+------------+ | 1 | Mike | 23 | | 2 | John | 26 | | 3 | Sam | 19 | | 4 | Carol | 27 | | 5 | Bob | 24 | +-----------+-------------+------------+ 5 rows in set (0.00 sec)
4. concat()으로 CSV 형식 출력하기
이제 concat() 함수를 사용해 각 행의 값을 쉼표로 구분된 CSV 형식의 문자열로 변환하여 화면에 출력해 보겠습니다.
mysql> select concat(StudentId,',',StudentName,',',StudentAge) as CSVFormat from CSVFormatOutputs;
실행 결과, 각 레코드가 CSV 형식으로 깔끔하게 표시되는 것을 확인할 수 있습니다.
+------------+ | CSVFormat | +------------+ | 1,Mike,23 | | 2,John,26 | | 3,Sam,19 | | 4,Carol,27 | | 5,Bob,24 | +------------+ 5 rows in set (0.00 sec)
참고 사항
concat() 함수는 인수 중 하나라도 NULL이면 전체 결과가 NULL로 반환됩니다. 따라서 NULL 값이 포함될 가능성이 있는 컬럼이라면 concat_ws() 함수를 사용하는 것이 좋습니다. concat_ws()는 첫 번째 인수로 구분자를 받고, NULL 값을 자동으로 건너뛰기 때문에 더 안전하게 CSV 형식을 만들 수 있습니다.
mysql> select concat_ws(',', StudentId, StudentName, StudentAge) as CSVFormat from CSVFormatOutputs;이처럼 concat() 또는 concat_ws() 함수를 활용하면 별도의 파일 export 과정 없이도 쿼리 결과를 즉시 CSV 형식으로 화면에 확인할 수 있습니다.