views:

3717

answers:

2

In MySql's interpreter, it's very easy to dump a table to the screen along with its field names.

There seems to be no simple way to export a table to a tab-delimted or CSV outfile including its column headers.

I'm trying to do this using only SQL or the Linux command line, without writing a program in another language.

Thank you

+3  A: 

Piping the query to the commandline client outputs a tab separated list with the column names as the first line

$ echo "select * from surveys limit 5" | mysql -uroot -pGandalf surveys
phone   param1  param2  param3  param4  p0      p1      p2      p3      audio4  code    time
XXXXXXXXX       2008-07-02      11:17:23        XXXXXXXX        SAT     -       -       -       -       -       ERROR   2008-07-02 12:18:32
XXXXXXXXX       2008-07-02      11:22:52        XXXXXXXX        SAT     -       -       -       -       -       COLGADO 2008-07-02 12:04:29
XXXXXXXXX       2008-07-02      11:41:29        XXXXXXXX        SAT     -       -       -       -       -       COLGADO 2008-07-02 12:07:22
XXXXXXXXX       2008-07-02      12:16:19        XXXXXXXX        SAT     1       1       1       9       XXXXXXXXX_4.wav     OK      2008-07-02 16:14:27
XXXXXXXXX       2008-07-02      08:21:25        XXXXXXXX        SAT     1       1       1       1       XXXXXXXXX_4.wav     OK      2008-07-02 12:29:40
Vinko Vrsalovic
I tested this and it worked as advertised
Dan Goldstein
+1  A: 

You can do this with the mysqldump command. Have a look at the --tab and --xml options.

Dana the Sane
I tested this and it did not give satisfactory results. Namely "sudo mysqldump --user=root --pass=mypass -T /home/mydir mydb mytable" yields "mysqldump: Got error: 1: Can't create/write to file '/home/mydir/mytable.txt' (Errcode: 13) when executing 'SELECT INTO OUTFILE'"
Dan Goldstein
You should not need to use sudo for this. Just make sure you're running mysqldump from an account that has permission to write to the output folder, that seems to be what the error is.
Dana the Sane
Ok, got this to work by creating a directory with 777 permissions. However, it did not output the column names, just the data.
Dan Goldstein
Make sure you check the top of the file, generally these tools dump the schema first then the data. If you want a tab delimited file with the columns in the header, you may have to use --xml and perform a 2nd conversion step.
Dana the Sane