将具有多个UNION的mysql查询的结果输出到CSV

时间:2019-04-29 08:11:56

标签: mysql

我想将使用多个联接(按分组和排序)的查询的结果输出到CSV文件中。

查询本身使用UNION生成结果集,空白行和总计行。

当我尝试使用UNION ALL将文件输出为CSV时,会出现错误

select "header1", "header2", "header3"
UNION ALL
(  
   select field1, field2, field3
   from tablename1
   UNION
   select "","",""
   UNION
   select "Total", field2, field3
)
into outfile 'c:\\data.csv' 
FIELDS TERMINATED BY ',' 
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n';

Err 1064: 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 'UNION (select "","","","","","","","","","","" ) ' at line <6>

预先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

请注意,如下所示:

select 1, 2, 3
union all
(
  select 0,4,6
  union
  select 1,1,1
)

不起作用。

您应该改用这样的派生表:

select 1, 2, 3
union all
select * from (
  select 0,4,6
  union
  select 1,1,1
) x