MYSQL表导出为CSV时如何处理空字段

vsdwdz23  于 2023-09-28  发布在  Mysql
关注(0)|答案(4)|浏览(156)

现在,当我将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  '"'
hwamh0ep

hwamh0ep1#

从MySQL documentation
如果FIELDS ESCAPED BY字符为空,则不会转义任何字符,并且NULL将输出为NULL,而不是\N。指定空转义符可能不是一个好主意,特别是如果数据中的字段值包含刚刚给出的列表中的任何字符。

5fjcxozz

5fjcxozz2#

艰难的道路:

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 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,'')
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  '"'

这将默认所有值为空字符串而不是NULL(“\N”)。

b4wnujal

b4wnujal3#

以防万一为了避免为每个变量输入“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
wtlkbnrh

wtlkbnrh4#

我也有这个问题,解决如下:

select ifnull(`addr`.`reference`, "") AS `reference`, data2 from ...

相关问题