- 类别:
:doc:`/sql-reference/functions-string`(通用)
CONCAT、||¶
连接一个或多个字符串,或连接一个或多个二进制值。
|| 运算符提供了替代的 CONCAT 语法,并且至少需要两个实参。
- 另请参阅:
语法¶
CONCAT( <expr> [ , <expr> ... ] )
<expr> || <expr> [ || <expr> ... ]
实参¶
exprThe input expressions must be all strings, or all binary values.
返回¶
The data type of the returned value is the same as the data type of the input values.
If any input value is NULL, the function returns NULL.
使用说明¶
元数据函数(如 GET_DDL)仅接受常量作为输入。连接的输入会生成错误。
排序规则详细信息¶
The collation specifications of all input arguments must be compatible.
The collation of the result of the function is the highest-precedence collation of the inputs.
示例¶
连接两个字符串:
SELECT CONCAT('George Washington ', 'Carver');
+----------------------------------------+
| CONCAT('GEORGE WASHINGTON ', 'CARVER') |
|----------------------------------------|
| George Washington Carver |
+----------------------------------------+
连接五个字符串,其中三个使用 会话变量:
SET var_first_name = 'George';
SET var_middle_name = 'Washington';
SET var_last_name = 'Carver';
SELECT CONCAT($var_first_name, ' ', $var_middle_name, ' ', $var_last_name) AS concat_name;
+--------------------------+
| CONCAT_NAME |
|--------------------------|
| George Washington Carver |
+--------------------------+
连接两个 VARCHAR 列。首先,创建一个表并插入数据:
CREATE OR REPLACE TABLE concat_function_example (s1 VARCHAR, s2 VARCHAR, s3 VARCHAR);
INSERT INTO concat_function_example (s1, s2, s3) VALUES
('co', 'd', 'e'),
('Colorado ', 'River ', NULL);
运行查询:
SELECT CONCAT(s1, s2)
FROM concat_function_example;
+-----------------+
| CONCAT(S1, S2) |
|-----------------|
| cod |
| Colorado River |
+-----------------+
连接两个以上的字符串:
SELECT CONCAT(s1, s2, s3)
FROM concat_function_example;
+--------------------+
| CONCAT(S1, S2, S3) |
|--------------------|
| code |
| NULL |
+--------------------+
使用 IFF 与 CONCAT 函数连接不是 NULL 的字符串:
SELECT CONCAT(
IFF(s1 IS NULL, '', s1),
IFF(s2 IS NULL, '', s2),
IFF(s3 IS NULL, '', s3)) AS concat_non_null_strings
FROM concat_function_example;
+-------------------------+
| CONCAT_NON_NULL_STRINGS |
|-------------------------|
| code |
| Colorado River |
+-------------------------+
使用 || 连接运算符而不是函数:
SELECT 'This ' || 'is ' || 'another ' || 'concatenation ' || 'technique.';
+--------------------------------------------------------------------+
| 'THIS ' || 'IS ' || 'ANOTHER ' || 'CONCATENATION ' || 'TECHNIQUE.' |
|--------------------------------------------------------------------|
| This is another concatenation technique. |
+--------------------------------------------------------------------+