【问题标题】:MySQL export to CSV - fields contain " but are not escaped by "MySQL 导出到 CSV - 字段包含“但不被”转义
【发布时间】:2016-08-24 16:23:52
【问题描述】:

我有一些表包含带有双引号的字段,但它们是“英寸”的名称或缩写的一部分,“不要转义该字段。

我需要将其导出到 CSV 文件,但 MySQL 不断破坏 " 处的字段并在 CSV 中创建额外的列。我如何处理 " 字段值内?

代码:

select
   makers.maker_name,
   baits.bait,
   depth_line.depth,
   depth_line.lineout a
from makers
   inner join baits on makers.maker_id = baits.maker_id
   inner join depth_line on depth_line.bait_id = baits.bait_id
order by
   makers.maker_name asc,
   baits.bait,
   depth_line.depth asc
into outfile '/tmp/muskie.csv'
fields terminated by ',';

诱饵表中的样本数据:

【问题讨论】:

    标签: mysql


    【解决方案1】:

    我无法重现该问题。

    mysql> SELECT VERSION();
    +-----------+
    | VERSION() |
    +-----------+
    | 5.7.12    |
    +-----------+
    1 row in set (0.00 sec)
    
    mysql> DROP TABLE IF EXISTS `table0`;
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> CREATE TABLE IF NOT EXISTS `table0` (
        ->   `column0` VARCHAR(255) DEFAULT NULL,
        ->   `column1` VARCHAR(255) DEFAULT NULL
        -> );
    Query OK, 0 rows affected (0.01 sec)
    
    mysql> INSERT INTO `table0`
        ->   (`column0`, `column1`)
        -> VALUES
        ->   ('"inches"', 'inches'),
        ->   ('4"', 'Lure name, 8", char, char'),
        ->   ('"VALUE 1"', 'NEW VALUE 1');
    Query OK, 3 rows affected (0.00 sec)
    Records: 3  Duplicates: 0  Warnings: 0
    
    mysql> SELECT
        ->   `column0`,
        ->   `column1`
        -> FROM
        ->   `table0`
        -> INTO OUTFILE '/path/to/file/muskie.csv'
        -> FIELDS TERMINATED BY ',';
    Query OK, 3 rows affected (0.00 sec)
    

    文件:/path/to/file/muskie.csv

    "inches",inches
    4",Lure name\, 8"\, char\, char
    "VALUE 1",NEW VALUE 1
    

    更新

    也许添加参数OPTIONALLY ENCLOSED BY '"'会很有用:

    SELECT
      `column0`,
      `column1`
    FROM
      `table0`
    INTO OUTFILE '/path/to/file/muskie.csv'
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"';
    

    文件:/path/to/file/muskie.csv

    "\"inches\"","inches"
    "4\"","Lure name, 8\", char, char"
    "\"VALUE 1\"","NEW VALUE 1"
    

    【讨论】:

    • 我在相关字段中的数据看起来更像:'4"' 或 'Lure name, 8"'...所以字段中某处只有一个 "。
    • 对不起,双引号不是我的问题,是字段中的逗号让我很痛苦。所以单个字段可能包含'char,char'。查询用逗号分割字段。
    猜你喜欢
    • 1970-01-01
    • 2014-06-16
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    • 2018-04-12
    相关资源
    最近更新 更多