将MYSQL表导出为CSV时如何处理空字段
Posted
技术标签:
【中文标题】将MYSQL表导出为CSV时如何处理空字段【英文标题】:How to handle null field when exporting MYSQL tables to CSV 【发布时间】:2014-08-06 16:26:01 【问题描述】:现在,当我将 mysql 表导出到 CSV 文件时,我得到 \N 表示数据库中的 NULL 字段,这是预期的。将表导出到 csv 时,是否有办法将 \N 输出更改为空字符串?
谢谢
SELECT 'CU_CustomerID','CU_UserName','CU_Password','CU_Email','CU_Company','CU_Comment','CU_LastBasket','CON_FirstName','CON_MiddleI','CON_LastName','CON_Address1','CON_Address2','CON_City','CON_State','CON_Province','CON_Country','CON_Zip','CON_Phone1','CON_Phone2'
UNION
SELECT T1.CU_CustomerID,T1.CU_UserName,T1.CU_Password,T1.CU_Email,T1.CU_Company,T1.CU_Comment,T1.CU_ShopperPoints,T2.CON_FirstName,T2.CON_MiddleI,T2.CON_LastName,T2.CON_Address1,T2.CON_Address2,T2.CON_City,T2.CON_State,T2.CON_Province,T2.CON_Country,T2.CON_Zip,T2.CON_Phone1,T2.CON_Phone2
FROM CUSTOMERS AS T1
INNER JOIN CONTACT AS T2 ON T1.CU_CustomerID = T2.CON_CustomerID
WHERE T1.CU_CustomerID BETWEEN 0 AND 1000
INTO OUTFILE 'customers.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
【问题讨论】:
【参考方案1】:来自 MySQL documentation
如果 FIELDS ESCAPED BY 字符为空,则没有字符被转义 并且 NULL 输出为 NULL,而不是 \N。指定一个空的转义字符可能不是一个好主意, 特别是如果您的数据中的字段值包含刚刚给出的列表中的任何字符。
【讨论】:
那么在我的情况下,如何将 NULL 字段输出到空字符串而不是 \N?确切的查询是什么?谢谢 @user2700690 请添加您的声明,然后我可以更正它。 @user2700690 在查询末尾添加ESCAPED BY "";
。
现在确定它的返回值“NULL”而不是“\N”。有没有办法为 NULl 字段返回空字符串?
@user2700690 在选择中执行:SELECT ifNull'CU_CustomerID',''),ifnull('CU_UserName',''),...
【参考方案2】:
以防万一。为了避免为每个变量都输入“ifnull(var,'') as var”,可以使用:
SELECT GROUP_CONCAT(CONCAT("IFNULL(",COLUMN_NAME,",'') AS ", COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '<table name>'
AND TABLE_SCHEMA = '<schema name>'
ORDER BY ORDINAL_POSITION
【讨论】:
【参考方案3】:硬道:-
SELECT 'CU_CustomerID','CU_UserName','CU_Password','CU_Email','CU_Company','CU_Comment','CU_LastBasket','CON_FirstName','CON_MiddleI','CON_LastName','CON_Address1','CON_Address2',' CON_City','CON_State','CON_Province','CON_Country','CON_Zip','CON_Phone1','CON_Phone2' 联盟 SELECT COALESCE(T1.CU_CustomerID,''),COALESCE(T1.CU_UserName,''),COALESCE(T1.CU_Password,''),COALESCE(T1.CU_Email,''),COALESCE(T1.CU_Company,'') ,COALESCE(T1.CU_Comment,''),COALESCE(T1.CU_ShopperPoints,''),COALESCE(T2.CON_FirstName,''),COALESCE(T2.CON_MiddleI,''),COALESCE(T2.CON_LastName,'') ,COALESCE(T2.CON_Address1,''),COALESCE(T2.CON_Address2,''),COALESCE(T2.CON_City,''),COALESCE(T2.CON_State,''),COALESCE(T2.CON_Province,'') ,COALESCE(T2.CON_Country,''),COALESCE(T2.CON_Zip,''),COALESCE(T2.CON_Phone1,''),COALESCE(T2.CON_Phone2,'') 来自 T1 的客户 T1.CU_CustomerID = T2.CON_CustomerID 上的 T2 内部连接联系人 T1.CU_CustomerID 介于 0 和 1000 之间的位置 INTO OUTFILE 'customers.csv' 以“,”结尾的字段 由'"'包围这会将所有值默认为空字符串,而不是 NULL ('\N')。
【讨论】:
【参考方案4】:我也遇到了这个问题,解决方法如下:
select ifnull(addr
.reference
, "") AS reference
, data2 from ...
【讨论】:
以上是关于将MYSQL表导出为CSV时如何处理空字段的主要内容,如果未能解决你的问题,请参考以下文章
将 OpenOffice Calc 文件导出为 PDF 时如何处理打印区域?