使用this solution,我尝试使用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的单个列?
答案 0 :(得分:116)
如果两列都可以包含NULL
,但您仍希望将它们合并为单个字符串,则最简单的解决方案是使用CONCAT_WS():
SELECT FirstName AS First_Name
, LastName AS Last_Name
, CONCAT_WS('', ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone
FROM TABLE1
这样您就不必分别检查每列的NULL
-
或者,如果两列实际定义为NOT NULL
,CONCAT()就足够了:
SELECT FirstName AS First_Name
, LastName AS Last_Name
, CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone
FROM TABLE1
对于COALESCE
,这是一个有点不同的野兽:给定参数列表,它返回的第一个不是NULL
。
答案 1 :(得分:6)
您无需列出ContactPhoneAreaCode1和ContactPhoneNumber1
SELECT FirstName AS First_Name,
LastName AS Last_Name,
COALESCE(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone
FROM TABLE1
答案 2 :(得分:5)
您无需单独选择列,以便在CONCAT中使用它们。只需删除它们,您的查询就会变为:
SELECT FirstName AS First_Name
, LastName AS Last_Name
, CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone
FROM TABLE1
答案 3 :(得分:1)
如果是NULL
列,最好使用这样的IF
子句,它结合了CONCAT
和COALESCE
这两个函数,并在列之间使用特殊字符结果如空格或'_'
SELECT FirstName , LastName ,
IF(FirstName IS NULL AND LastName IS NULL, NULL,' _ ',CONCAT(COALESCE(FirstName ,''), COALESCE(LastName ,'')))
AS Contact_Phone FROM TABLE1