MySQL 查询到 CSV

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21107279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 19:49:14  来源:igfitidea点击:

MySQL Query to CSV

mysqlsqlcsv

提问by vinay

Is there an easy way to run a MySQLquery from the linuxcommand line and output the results in csv format?

有没有一种简单的方法可以从命令行运行MySQL查询linux并以 csv 格式输出结果?

Here's what I'm doing now:

这是我现在正在做的事情:

mysql -u uid -ppwd -D dbname << EOQ | sed -e 's/        /,/g' | tee
list.csv select id, concat("\"",name,"\"") as name from students EOQ

It gets messy when there are a lot of columns that need to be surrounded by quotes, or if there are quotes in the results that need to be escaped.

当有很多列需​​要用引号括起来,或者结果中有引号需要转义时,它会变得混乱。

回答by Doug

You can use "INTO OUTFILE"

您可以使用“ INTO OUTFILE

I.e.

IE

SELECT a,b,c FROM my_table INTO OUTFILE '/ca.csv' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'; 

This will create a file "ca.csv" with a comma between each line. There are a few other options like escaping field values, but that should be enough to get you started.

这将创建一个文件“ca.csv”,每行之间有一个逗号。还有一些其他选项,例如转义字段值,但这应该足以让您入门。

The whole thing:

整个东西:

mysql -u uid -ppwd -D dbname -e "SELECT a,b,c FROM my_table INTO OUTFILE '/ca.csv' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';"

mysql -u uid -ppwd -D dbname -e "SELECT a,b,c FROM my_table INTO OUTFILE '/ca.csv' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';"

EDIT:- A link for you to look at: SELECT INTO

编辑:- 供您查看的链接:SELECT INTO

To escape the fields, you would need to add FIELDS ESCAPED BY '"'- This would add double quotes

要转义字段,您需要添加FIELDS ESCAPED BY '"'- 这将添加双引号