mysql导出到del不加引号,将MySQL导出为CSV,有些列带引号,有些不带引号

I am exporting a MySQL table and I want to export the integer type columns without double quotes but the varchar type columns with double quotes. I need to do this to have the correct formatting for the next step in my work. Can this be done in MySQL? I know I could probably do this in a python script but the csv files are pretty large (>1 GB) so I think it might take awhile to do that. Anyway, is this possible using MySQL Queries?

Here's my current export script format:

SELECT

'column_name_1',

'column_name_2',

...

'column_name_n'

UNION ALL

SELECT *

FROM table

INTO OUTFILE 'table.csv'

FIELDS TERMINATED BY ','

LINES TERMINATED BY '\n';

If it helps, here is the table (more importantly, the types involved) I am trying to export:

+-------------------------+------------------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+-------------------------+------------------+------+-----+---------+-------+

| field_1 | int(10) unsigned | NO | MUL | 0 | |

| field_2 | int(10) unsigned | NO | MUL | NULL | |

| field_3 | int(10) unsigned | NO | | NULL | |

| field_4 | char(1) | NO | | NULL | |

| field_5 | int(10) unsigned | NO | | NULL | |

| field_6 | varchar(4) | NO | | | |

| field_7 | char(1) | NO | | Y | |

| field_8 | varchar(20) | NO | | | |

| field_9 | varchar(200) | NO | | | |

+-------------------------+------------------+------+-----+---------+-------+

EDIT 1: I tried OPTIONALLY ENCLOSED BY '"' as suggested in an answer, but when I add that to the script, it double quotes every column, not just the string (or varchar) columns. Any idea why it might do this?

解决方案

use the OPTIONALLY ENCLOSED BY clause.

SELECT *

FROM table

INTO OUTFILE 'table.csv'

FIELDS TERMINATED BY ','

OPTIONALLY ENCLOSED BY '"'

LINES TERMINATED BY '\n';

The OPTIONALLY modifier makes it do this only for string columns.

You also need to leave out the subquery that returns the header line. The problem is that all rows of a union need to have the same types in the columns, so it's converting all the non-strings to strings to match the header line.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值