Thursday, October 23, 2008

about exporting query results in mysql

Though dumping database can be done easily in mysql by the mysqldump command, it can not be used to export query result into files. Using sql to do data preprocessing is very useful approach in various cases. After reading the mysql cookbook, there're two ways:
1. select ... into outfile 'filename'
this is a specific sql pattern supported by the mysql. when we're work on the server machine and wanna export the file on the sever itself, then we can use this command. The file in default will be output into the data directory of mysql installation. Another thing is we need to give mysql command the file r/w privileges. 

2. mysql -e 'select ....' -N dbname > filename -u user -p
if we can not use the server machine, for example accessing the server from a client machine, then this command can produce what we want. -e specified the query in quotes. -N tells mysql to produce the output file without the column names. dbname is the database name where the query run against, -u is follows the user who have privilege to access the db, -p is the password. 

both commands will add the tab mark between different files and new line mark between different rows by default. there're lots of commands to change the output format, that is omitted here. 

No comments:

Post a Comment