简体   繁体   English

如何在select语句中连接可能包含NULL值的两列?

[英]How to concatenate two columns that might contain NULL values in a select statement?

I tried with:我试过:

SELECT CONCAT(col1, col2) AS NewCol FROM tableName

It works only if col1 and col2 are not null, else NewCol becomes null, even if one of col1 and col2 is not null.只有当 col1 和 col2 不为空时它才有效,否则 NewCol 变为空,即使 col1 和 col2 之一不为空。 I want it to display whatever value that is available.我希望它显示任何可用的值。

Use CONCAT_WS .使用CONCAT_WS

SELECT CONCAT_WS('', col1, col2) AS NewCol FROM tableName

It would return an empty string in case both the values are null .如果两个值都为null ,它将返回一个空字符串。

Documentation:文档:

CONCAT_WS(separator,str1,str2,...) CONCAT_WS(分隔符,str1,str2,...)

CONCAT_WS() stands for Concatenate With Separator and is a special form of CONCAT(). CONCAT_WS() 代表 Concatenate With Separator,是 CONCAT() 的一种特殊形式。 The first argument is the separator for the rest of the arguments.第一个参数是其余参数的分隔符。 The separator is added between the strings to be concatenated.在要连接的字符串之间添加分隔符。 The separator can be a string, as can the rest of the arguments.分隔符可以是字符串,其余参数也可以。 If the separator is NULL, the result is NULL.如果分隔符为 NULL,则结果为 NULL。

You can use CONCAT_WS .您可以使用CONCAT_WS its NULL safe.它的 NULL 安全。 the first argument is the separator.第一个参数是分隔符。

sample样本

MariaDB [l]> SELECT CONCAT_WS('',NULL,'123');
+--------------------------+
| CONCAT_WS('',NULL,'123') |
+--------------------------+
| 123                      |
+--------------------------+
1 row in set (0.00 sec)

MariaDB [l]>

你也可以使用

SELECT ISNULL([col1],'') + ISNULL([col2],'') AS NewCol FROM tableName

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM