在MySql的解释器中,将表格及其字段名称转储到屏幕上非常容易.
似乎没有简单的方法将表导出到制表符分隔或CSV输出文件,包括其列标题.
我正在尝试仅使用SQL或Linux命令行执行此操作,而无需使用其他语言编写程序.
谢谢
将查询管道输出到命令行客户端会输出一个以制表符分隔的列表,其中列名称为第一行
$ echo "select * from surveys limit 5" | mysql -uroot -pGandalf surveys phone param1 param2 param3 param4 p0 p1 p2 p3 audio4 code time XXXXXXXXX 2008-07-02 11:17:23 XXXXXXXX SAT - - - - - ERROR 2008-07-02 12:18:32 XXXXXXXXX 2008-07-02 11:22:52 XXXXXXXX SAT - - - - - COLGADO 2008-07-02 12:04:29 XXXXXXXXX 2008-07-02 11:41:29 XXXXXXXX SAT - - - - - COLGADO 2008-07-02 12:07:22 XXXXXXXXX 2008-07-02 12:16:19 XXXXXXXX SAT 1 1 1 9 XXXXXXXXX_4.wav OK 2008-07-02 16:14:27 XXXXXXXXX 2008-07-02 08:21:25 XXXXXXXX SAT 1 1 1 1 XXXXXXXXX_4.wav OK 2008-07-02 12:29:40
这个小脚本应该这样做:
- 1.在这里选择表格和输出文件/这应该是唯一的输入
select 'mytable' into @tableName; select 'c://temp/test.csv' into @outputFile;
- 2.以适合查询的格式获取列名称
select group_concat(concat("'",column_name, "'")) into @columnNames from information_schema.columns where table_name=@tableName;
- 3.构建查询
SET @query = CONCAT( "select * from ((SELECT ",@columnNames,") UNION (SELECT * FROM `",@tableName,"`)) as a INTO OUTFILE '", @outputFile, "'");
- 4.执行查询
PREPARE stmt FROM @query; EXECUTE stmt;