Output MySQL query to CSV file

December 6th, 2013

I wanted to export some data from my MySQL database because I didn't want to use the app that populated the database any more.

Instead of creating a script to make the query, structure the output and write it to a file I found out that I could make MySQL do all the work for me, Afterwards I could grab the file in the /tmp folder. The code is below, it should be easy to understand.

Btw. I executed this on MySQL mysql Ver 14.14 Distrib 5.1.72, for debian-linux-gnu (x86_64) using readline 6.1.

SELECT time,rpl.name,rpa.name,amount 
FROM receipts_receipt rr join receipts_payer rpa join receipts_place rpl 
WHERE rr.place_id = rpl.id and rr.payer_id = rpa.id
INTO OUTFILE '/tmp/receipts.csv' 
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"' 
LINES TERMINATED BY '\n';

Categories

IT

Tags