19

有没有办法做类似下面的事情?这不起作用,但显示了我想要做的事情

SET @OutputPath = '/Users/jo/Documents'
SET @fullOutputPath = CONCAT(@OutputPath,'/','filename.csv')
SET @fullOutputPath2 = CONCAT(@OutputPath,'/','filename2.csv')

SELECT * INTO OUTFILE @fullOutputPath
FIELDS TERMINATED BY ',' 
OPTIONALLY ENCLOSED BY '"'
FROM database.tableName;

SELECT * INTO OUTFILE @fullOutputPath2
FIELDS TERMINATED BY ',' 
OPTIONALLY ENCLOSED BY '"'
FROM database.tableName2;
4

4 回答 4

30

编辑:将数据(例如表格)保存到文件中而不使用变量(仅常量值)

-- folder_path could could be like => c:/users/sami
-- choose the directory/folder already available in system
-- and make sure you have access to write the file there

SELECT * INTO OUTFILE 'folder_path/filename.csv'
FIELDS TERMINATED BY ',' 
OPTIONALLY ENCLOSED BY '"'
FROM database.tableName;

现在使用变量

无论何时必须在 sql 中使用变量名,都需要动态 sql(仅适用于存储过程,既不适用于简单的 sql 查询,也不适用于触发器或函数)

SET @OutputPath := 'Users/jo/Documents'; //or any folder_path
SET @fullOutputPath := CONCAT(@OutputPath,'/','filename.csv');
SET @fullOutputPath2 := CONCAT(@OutputPath,'/','filename2.csv');

set @q1 := concat("SELECT * INTO OUTFILE ",@fullOutputPath,
" FIELDS TERMINATED BY ',' 
OPTIONALLY ENCLOSED BY '\"'
FROM database.tableName");

set @q2 := concat("SELECT * INTO OUTFILE ",@fullOutputPath2,
" FIELDS TERMINATED BY ',' 
OPTIONALLY ENCLOSED BY '\"'
FROM database.tableName2");

prepare s1 from @q1;
execute s1;deallocate prepare s1;

prepare s1 from @q2;
execute s1;deallocate prepare s1;

正如您已经在查询中拥有两者一样'"因此我使用并使用 \ 来连接您的查询"以转义您的原始"字符,以确保其用作文字字符而不用于连接

我刚才讲了variablein sql的使用。首先,您应该确保您的查询是否像顶部的示例一样工作(不使用变量)

结论:如果您的上述查询工作正常,那么考虑到您在某些存储过程中使用它,我告诉的动态 sql 也可以正常工作。

于 2012-11-25T08:21:33.300 回答
2

我的卡玛很低,所以我发布的答案应该作为对 Sami 帖子的评论 - 您需要用引号将文件名括起来(注意在 @fullOutputPath 之前和之后添加 '):

set @q1 := concat("SELECT * INTO OUTFILE '",@fullOutputPath,
"' FIELDS TERMINATED BY ',' 
OPTIONALLY ENCLOSED BY '\"'
FROM database.tableName");
于 2013-10-15T08:57:27.700 回答
2

如果您想从 bash 中执行此操作,即将 csv 中的 mysql 中的一些数据导出到具有动态名称的文件中,它可能更容易且更具可读性,如下所示。

带有嵌入式 bash 变量的 SQL:

where (e.timestamp >= ${begin_ts} and e.timestamp < ${end_ts}) order by ed.timestamp ASC ) a
INTO OUTFILE '${export_path}' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

以及运行 sql 文件的 bash 脚本。请注意评估 sql 脚本并替换变量的 envsubst 命令。

#!/bin/bash
mysql_db="dbname"
mysql_user="mysqlpass"
mysql_pass="password"
export_path="./data.csv"
begin_ts="1478278490"
current_ts=$(date +%s -u)

sql=`export_path=${export_path} begin_ts=${last_ts} end_ts=${current_ts} envsubst < export.sql`
mysql $mysql_db -u $mysql_user -p$mysql_pass -e"${sql}"
于 2016-11-04T17:42:44.403 回答
-1

您不能在 mysql CLI 中执行此操作,但以这种方式可以工作

mysql -e "SELECT * FROM database.tableName;" -u user -p database > filename.csv
于 2012-11-25T04:08:53.820 回答