본문 바로가기

데이터베이스(DA, AA, TA)/MySQL

[MySQL] SELECT 결과물을 파일로 저장하기.

DB 데이터를 파일로 추출하여 엑셀파일로 작업해야하는 경우가 생기기도 합니다. 아래 쿼리는 DB 명령프롬프트 창에서 해당 SELECT문을 파일로 저장하는 쿼리 예제입니다.


SELECT

users.id, ifnull(payment.payment_count, 0) as payment_count

INTO OUTFILE '20170101_paycount.log' FIELDS TERMINATED BY '|'

FROM

(select id from users where (withdraw_date > '2016-01-01' and withdraw_date < '2016-12-31') or withdraw_date is null) users

LEFT JOIN

(select order_user_id as id, count(payment_date) payment_count from tb_order where order_status='Y' and payment_date > '2016-01-01' and payment_date < '2016-12-31' group by order_user_id) payment

ON users.id = payment.id

ORDER BY id ASC;



위와 같이 쿼리를 입력하면 컬럼별 | 구분자를 가지는 SELECT 결과에 따른 파일이 만들어집니다.