码迷,mamicode.com
首页 > 数据库 > 详细

MySQL通过自增一列在Select ... into outfile...里面实现CSV导出带字段的效果

时间:2014-07-27 11:20:42      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:

CSV的样例中Select ... into outfile...是不带字段名的,只导出数据,所以需要自己想另外的办法实现,这里有一个笨招,自己构造一个字段列,示例如下:

1,创建测试表数据
CREATE TABLE test.c SELECT 1 AS pid,1 AS item,15.0 AS wgt UNION ALL
SELECT 1 AS pid,2 AS item,20.0 AS wgt UNION ALL
SELECT 1 AS pid,3 AS item,30.0 AS wgt UNION ALL
SELECT 1 AS pid,4 AS item,29.0 AS wgt;
SELECT * FROM test.c;


mysql> SELECT * FROM test.c;
+-----+------+------+
| pid | item | wgt  |
+-----+------+------+
|   1 |    1 | 15.0 | 
|   1 |    2 | 20.0 | 
|   1 |    3 | 30.0 | 
|   1 |    4 | 29.0 | 
+-----+------+------+
4 ROWS IN SET (0.00 sec)


2,通过union all实现字段列,并且排在第一行

SELECT * FROM (
SELECT ‘pid‘ AS pid,‘item‘ AS item,‘wgt‘ AS wgt
UNION ALL
SELECT * FROM test.c
)a INTO OUTFILE ‘/tmp/c.csv‘ 
 FIELDS TERMINATED BY ‘,‘ 
 OPTIONALLY ENCLOSED BY ‘"‘
  LINES TERMINATED BY ‘\n‘;

执行如下:
mysql> SELECT * FROM (
    -> SELECT ‘pid‘ AS pid,‘item‘ AS item,‘wgt‘ AS wgt
    -> UNION ALL
    -> SELECT * FROM test.c
    -> )a INTO OUTFILE ‘/tmp/c.csv‘ 
    ->  FIELDS TERMINATED BY ‘,‘ 
    ->  OPTIONALLY ENCLOSED BY ‘"‘
    ->   LINES TERMINATED BY ‘\n‘;
Query OK, 5 rows affected (0.00 sec)

3,去打开c.csv文件查看效果
bubuko.com,布布扣

MySQL通过自增一列在Select ... into outfile...里面实现CSV导出带字段的效果

标签:

原文地址:http://blog.csdn.net/mchdba/article/details/38166443

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!