从 MySQL 查询导出 CSV 时将输出文件 FILE_PATH 作为参数传递

Pass outfile FILE_PATH as parameter when exporting CSV from MySQL query

如何将 outfile 文件路径传递给 MySQL?我试过下面的。没用。

我的SQL文件

SET @query = CONCAT('SELECT *
FROM
     `registered_user`
INTO OUTFILE ',@output_location,' FIELDS TERMINATED BY \',\'
LINES TERMINATED BY \'\n\'');

PREPARE stmt FROM @query;
      EXECUTE stmt;
      DEALLOCATE PREPARE stmt;

我的命令行命令

mysql -u root -p test -e "set @output_location= '/var/tmp/out.csv'; source test2.sql;"

我收到以下错误

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/var/tmp/out.csv FIELDS TERMINATED BY ','
LINES TERMINATED BY '
'' at line 12

如果我只给 out.csv 就可以了。但我不知道文件存储在哪里。我在上面的命令中是否遗漏了任何转义序列?

This problem 已报告给 MySQL。但是有解决办法吗?

您可以通过选择 select @query 其构造方式等查询来简单地进行调试。

concat 中有引号时,请尝试使用双引号 " 而不是单引号 '。这将避免丢失您现在拥有的 '。并且不要忘记在 concat\n

时转义 \n
SET @query = CONCAT("SELECT *
FROM
     `registered_user`
INTO OUTFILE '",@output_location,"'  -- you need to enclose path with quotes
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'");

PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;