If we want to generate a CSV file directly from MySQL with column headings as the first row and a filename generated dynamically in the script, there are a few caveats which this snippet covers. These are described in full in long.sql amongst the comments and references.
long.sql- The script with all the comments and explanation of what/why.short.sql- The script that has no comments and is as brief as possible to be used as a template.
- Copy
short.sqlto a new.sqlfile in a location that is readable by the user running the MySQL process.