Home  >  Article  >  Database  >  How can we export the data to a CSV file with the column headers as the first row?

How can we export the data to a CSV file with the column headers as the first row?

WBOY
WBOYforward
2023-08-30 15:01:061436browse

我们如何将数据导出到 CSV 文件,并将列标题作为第一行?

In order to add column values, we need to use UNION statement. This can be demonstrated with the help of the following example -

Example

In this example, the data from student_info will be exported to a CSV file. The first row of the CSV file will be the column names.

mysql>(SELECT 'id', 'Name', 'Address', 'Subject')UNION(SELECT id, Name, Address, Subject From student_info INTO OUTFILE 'C:/mysql/bin/mysql-files/student_25.CSV'
FIELDS ENCLOSED BY '"' TERMINATED BY ';' ESCAPED BY '"' LINES TERMINATED BY '\r');
Query OK, 7 rows affected (0.04 sec)

After executing the above query, MySQL creates the Student_25.CSV file with the following values ​​-

id;    "Name";      "Address";      "Subject"
101;   "YashPal";   "Amritsar";     "History"
105;   "Gaurav";    "Chandigarh";   "Literature"
125;   "Raman";     "Shimla";       "Computers"
130;   "Ram";       "Jhansi";       "Computers"
132;   "Shyam";     "Chandigarh";   "Economics"
133;   "Mohan";     "Delhi";        "Computers"

The above is the detailed content of How can we export the data to a CSV file with the column headers as the first row?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete