首页 > 代码库 > MySQL通过自增一列在Select ... into outfile...里面实现CSV导出带字段的效果
MySQL通过自增一列在Select ... into outfile...里面实现CSV导出带字段的效果
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文件查看效果
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文件查看效果
MySQL通过自增一列在Select ... into outfile...里面实现CSV导出带字段的效果
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。