mysql – 如何使用引号括起但不包含正文字段的标题标签选择INTO OUTFILE?

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

我希望正文中的行是“可选地用双引号括起来的”.不应包含数值.没有标题就很容易做到.但是,当您使用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”之后结束.我只是放了第3行的一部分.

"         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      ,
最佳答案
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

转载注明原文:mysql – 如何使用引号括起但不包含正文字段的标题标签选择INTO OUTFILE? - 代码日志