我使用以下SQL代码段将表转储为CSV文本文件:
SELECT * FROM brand INTO OUTFILE“ e:/brand.csv”字段以’,’结尾,’‘’以’\ n’结尾;
但是,这种方法不会在CSV文件的开头添加列名。我的问题是如何也选择所有列/字段名称,就像phpMyAdmin在导出表并选择“在第一行中放入字段名称”时所做的一样。
我想出了一种方法,只要您运行的是MySQL 5或更高版本,就必须手动输入这些名称。它是作为bash脚本编写的,可以在unix命令行上运行:
DBNAME=<database_name> TABLE=<table_name> FNAME=/path/to/output/dir/$(date +%Y.%m.%d)-$DBNAME.csv #(1)creates empty file and sets up column names using the information_schema mysql -u <username> -p<password> $DBNAME -B -e "SELECT COLUMN_NAME FROM information_schema.COLUMNS C WHERE table_name = '$TABLE';" | awk '{print $1}' | grep -iv ^COLUMN_NAME$ | sed 's/^/"/g;s/$/"/g' | tr '\n' ',' > $FNAME #(2)appends newline to mark beginning of data vs. column titles echo "" >> $FNAME #(3)dumps data from DB into /var/mysql/tempfile.csv mysql -u <username> -p<password> $DBNAME -B -e "SELECT * INTO OUTFILE '/var/mysql/tempfile.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' FROM $TABLE;" #(4)merges data file and file w/ column names cat /var/mysql/tempfile.csv >> $FNAME #(5)deletes tempfile rm -rf /var/mysql/tempfile.csv
虽然不是最优雅的解决方案,但我敢肯定,知道SQL和/或bash的人可以比我好一点的人将其压缩为一行…
它的作用是:
祝您好运,如果您整理了一下,请发表您的结果!