3

我不相信这个问题是重复的。

我希望正文中的行是“OPTIONALLY ENCLOSED BY”双引号。不应包含数值。没有标题很容易做到这一点。但是,当您使用 UNION 包含标题时,MySQL 现在将每一列视为字符串类型并将所有值括在引号中。

您可以像这样向 SELECT INTO OUTFILE 添加标题:

SELECT "id", "numerical_values", "string_values" #header section of csv
UNION ALL
SELECT `id`, `numerical_values`, `string_values` #body section of csv
INTO OUTFILE "/tmp/values.csv"
FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY "\n"
FROM `values_table`

同样,如果我省略标题,只会string_values用引号括起来。使用标题,所有列都被视为字符串列并将被封闭。

我试过这个:

SELECT '"', "id", ',"', "numerical_values", ',"', "string_values", '"' 
#added quotes/commas to header
UNION ALL
SELECT `id`, ',', `numerical_values`, ',"', `string_values`, '"'
#added commas, and add quotes around string_values
INTO OUTFILE "/tmp/values.csv"
FIELDS TERMINATED BY "" ENCLOSED BY '' #empty values for fields terminated and enclosed
# empty because manually selected in query
LINES TERMINATED BY "\n" 
FROM `values_table`

我认为这会起作用,但我最终得到了看起来像一堆额外的空白。这是来自我刚刚使用第二种方法创建的文件。标题行以“string7”结束。第一行数据在“207”之后结束。我只是把第三行的一部分。

"         num1","                                          string1","       num2","                                          string2","       num3","                                                                        string3","       num4","                                                                        string4","       num5","                                                                        string5","       num6","                                                                        string6","      string7""
33.95     ," 1023                                         ",  7.50      ,"  207-1023                                     ",  26.95     ,"2 1023                                                                     ",23.00     ,"3Wx4Hx4D                                                                   ",19.00     ,"1023                                                                       ",  0.00      ,"UPC: 123456789012                                                          "," 207      "       
40.95     ," 1058                                         ",  9.00      ,
4

1 回答 1

10
SELECT '"id"', '"numerical_values"', '"string_values"'
UNION ALL
SELECT id, numerical_values, CONCAT('"', REPLACE(string_values, '"', '""'), '"')
INTO OUTFILE '/tmp/values.csv'
FIELDS TERMINATED BY ',' ENCLOSED BY '' ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM values_table
于 2012-11-04T09:07:41.490 回答