mysql / export查询结果在csv文件中

时间:2017-07-25 14:42:50

标签: php mysql

我有mysql脚本,通过LEFT JOIN选择所需数据并将结果保存在csv文件中。但问题是结果文件中缺少列名。我做错了什么?

SELECT 
a.*, b.pr_name
INTO OUTFILE 'johnoggyresult3.csv'
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
FROM
    `fileb` AS b
LEFT JOIN
    `filea` AS a ON b.pr_hand_size = a.user_hand_size
ORDER BY
     a.user_id

1 个答案:

答案 0 :(得分:0)

只需使用SELECT添加列名称即可。这样的事情应该有效:

SELECT * 

INTO OUTFILE 'johnoggyresult3.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

FROM (
SELECT 'column1', 'column2'
UNION ALL
(SELECT 
a.column1, b.pr_name
FROM
    `fileb` AS b
LEFT JOIN
    `filea` AS a ON b.pr_hand_size = a.user_hand_size
ORDER BY
     a.user_id) AS q
)

请注意,在获取并排序结果并将标题附加到数据集之后,最终将转储到CSV。在添加带有标题的行之前,您还需要先对数据进行排序,否则标题也会被排序,并且可能位于数据集中间的某个位置,而不是像预期的那样位于顶部。