Home > Back-end >  MySql naming the automatically downloaded CSV file using first and last date
MySql naming the automatically downloaded CSV file using first and last date

Time:11-11

MySql query gives me data from the 2020-09-21 to 2022-11-02. I want to save the file as FieldData_20200921_20221102.csv. Mysql query

SELECT 'datetime','sensor_1','sensor_2'

UNION ALL

SELECT  datetime,sensor_1,sensor_2

FROM `field_schema`.`sensor_table`
INTO OUTFILE "FieldData.csv" 
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
;

Present output file: Presently I named the file as FieldData.csv and it is accordingly giving me the same. But I want the query to automatically append the first and last dates to this file, so, it helps me know the duration of data without having to open it.

Expected output file

FieldData_20200921_20221102.csv.

CodePudding user response:

MySQL's SELECT ... INTO OUTFILE syntax accepts only a fixed string literal for the filename, not a variable or an expression.

To make a custom filename, you would have to format the filename yourself and then write dynamic SQL so the filename could be a string literal. But to do that, you first would have to know the minimum and maximum date values in the data set you are dumping.

I hardly ever use SELECT ... INTO OUTFILE, because it can only create the outfile on the database server. I usually want the file to be saved on the server where my client application is running, and the database server's filesystem is not accessible to the application.

Both the file naming problem and the filesystem access problem are better solved by avoiding the SELECT ... INTO OUTFILE feature, and instead writing to a CSV file using application code. Then you can name the file whatever you want.

  • Related