MySQL SELECT AS将两列合并为一个

使用这个解决scheme ,我尝试使用COALESCE作为MySQL查询的一部分,该查询使用SELECT As输出到csv文件,以在导出数据时命名列名。

SELECT FirstName AS First_Name , LastName AS Last_Name , ContactPhoneAreaCode1 , ContactPhoneNumber1 , COALESCE(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone FROM TABLE1 

我想要3列:First_Name,Last_Name和Contact_Phone

我得到5列:First_Name,Last_Name,ContactPhoneAreaCode1,ContactPhoneNumber1和Contact_Phone

如何在查询中隐藏ContactPhoneAreaCode1,ContactPhoneNumber1到Contact_Phone的单个列的合并?

如果两列都可以包含NULL ,但您仍然想将它们合并到一个string中,最简单的解决scheme是使用CONCAT_WS()

 SELECT FirstName AS First_Name , LastName AS Last_Name , CONCAT_WS('', ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone FROM TABLE1 

这样你就不必单独检查每列的NULL

或者,如果两个列实际上定义为NOT NULLCONCAT()就足够了:

 SELECT FirstName AS First_Name , LastName AS Last_Name , CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone FROM TABLE1 

至于COALESCE ,它有点不同:给定参数列表,返回第一个不是NULL

您不需要单独select列以在CONCAT中使用它们。 只需删除它们,你的查询就会变成:

 SELECT FirstName AS First_Name , LastName AS Last_Name , CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone FROM TABLE1 

您不需要列出ContactPhoneAreaCode1和ContactPhoneNumber1

 SELECT FirstName AS First_Name, LastName AS Last_Name, COALESCE(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone FROM TABLE1 

NULL列的情况下,最好使用这样的IF子句,它结合了CONCATCOALESCE这两个function,并在结果(如空格或“_”)之间使用特殊的字符,

 SELECT FirstName , LastName , IF(FirstName IS NULL AND LastName IS NULL, NULL,' _ ',CONCAT(COALESCE(FirstName ,''), COALESCE(LastName ,''))) AS Contact_Phone FROM TABLE1