MySQL:使用标头动态导出CSV文件

时间:2015-07-17 12:03:12

标签: mysql csv

是否有使用列标题导出MySQL表中的数据?

我通过将标题硬编码到查询中找到了一种方法,但是如果表中有大约60列甚至100列,那么这是不可能的。

我尝试了下面的查询但是我无法得到结果,因为查询的第一部分返回表中所有标题的连接字符串。它没有给我一个理想的结果:

(select concat(group_concat(COLUMN_NAME separator ','), "\n")
    from information_schema.COLUMNS
    where table_name = '<table name>'
    and table_schema = '<DB name>'
    order by ORDINAL_POSITION) 
union all
(select * from <table name> into outfile "E:\\test.csv" fields terminated by "," lines terminated by "\n");

2 个答案:

答案 0 :(得分:3)

在mysql中获取表的字段名的方法很少,但是下面的方法最适合outfile。

根据日期戳动态创建csv文件的文件名,并使用此准备好的语句。

-- ensure mysql user has write permission on below location
SET @effectiveFileName = CONCAT('/home/myhome/temp-dev/', 'mytable','_', DATE_FORMAT(NOW(), '%Y-%m-%d'), '.csv');
-- group concat default is 1024, to avoid field names getting truncated we increase this value
SET SESSION group_concat_max_len = 10000;

SET @queryStr = (
    SELECT
    CONCAT('SELECT * INTO OUTFILE \'',
        @effectiveFileName,
        '\' FIELDS TERMINATED BY \',\' OPTIONALLY ENCLOSED BY \'"\' LINES TERMINATED BY \'\n\' FROM (SELECT ',
        GROUP_CONCAT(CONCAT('\'', COLUMN_NAME, '\'')),
        'UNION ALL SELECT * FROM myschema.mytable WHERE myschema.mytable.myfield <=\'',
        CURDATE(),
        '\') as tmp')
        FROM
            INFORMATION_SCHEMA.COLUMNS
        WHERE
            TABLE_NAME = 'mytable' AND
            TABLE_SCHEMA = 'myschema'
        ORDER BY ORDINAL_POSITION
    );
PREPARE stmt FROM @queryStr;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

下面是带有静态文件名的上述查询的简单版本。

-- group concat default is 1024, to avoid field names getting truncated we increase this value
SET SESSION group_concat_max_len = 10000;
SELECT 
CONCAT('SELECT * INTO OUTFILE \'/home/myuser/myfile.csv\' FIELDS TERMINATED BY \',\' OPTIONALLY ENCLOSED BY \'"\' ESCAPED BY \'\' LINES TERMINATED BY \'\n\' FROM (SELECT ',
        GROUP_CONCAT(CONCAT('\'', COLUMN_NAME, '\'')),
        ' UNION select * from YOUR_TABLE) as tmp')
FROM
    INFORMATION_SCHEMA.COLUMNS
WHERE
    TABLE_NAME = 'YOUR_TABLE'
    AND TABLE_SCHEMA = 'YOUR_SCHEMA'
ORDER BY ORDINAL_POSITION;

答案 1 :(得分:2)

(SELECT 'Order Number','Order Date','Status')
UNION 
(SELECT orderNumber,orderDate, status
FROM orders
INTO OUTFILE 'C:/tmp/orders.csv'
FIELDS ENCLOSED BY '"' TERMINATED BY ';' ESCAPED BY '"'
LINES TERMINATED BY '\r\n');