Is it possible to include the headers somehow when using the MySQL INTO OUTFILE
?
相关问题
- sqlyog export query result as csv
- NOT DISTINCT query in mySQL
- MySQL: conduct a basic search
- Why sometimes there is one of more gap(s) in the v
- mySQL alter table on update, current timestamp
You'd have to hard code those headers yourself. Something like:
I simply make 2 queries, first to get query output (limit 1) with column names (no hardcode, no problems with Joins, Order by, custom column names, etc), and second to make query itself, and combine files into one CSV file:
I faced similar problem while executing mysql query on large tables in NodeJS. The approach which I followed to include headers in my CSV file is as follows
Use OUTFILE query to prepare file without headers
Fetch column headers for the table used in point 1
Append the column headers to the file created in step 1 using prepend-file npm package
Execution of each step was controlled using promises in NodeJS.
I think if you use a UNION it will work:
I don't know of a way to specify the headers with the INTO OUTFILE syntax directly.
For complex select with ORDER BY I use the following:
This is an alternative cheat if you are familiar with Python or R, and your table can fit into memory.
Import the SQL table into Python or R and then export from there as a CSV and you'll get the column names as well as the data.
Here's how I do it using R, requires the RMySQL library:
It's a bit of a cheat but I found this was a quick workaround when my number of columns was too long to use the concat method above. Note: R will add a 'row.names' column at the start of the CSV so you'll want to drop that if you do need to rely on the CSV to recreate the table.