MySQL 可以用 || 拼接字符串吗?


可以的,借助sql_mode,你可以在 MySQL 中用 || 拼接字符串。将sql_mode设置为PIPES_AS_CONCAT。

语法如下

set sql_mode=PIPES_AS_CONCAT;

以下是用 || 拼接的语法。

SELECT ‘yourValue' || yourColumName AS anyAliasName FROM yourTableName;

为了理解上述语法,让我们创建一个表格。创建表格的查询如下

mysql> create table PipeConcatDemo
   - > (
   - > Name varchar(20)
   - > );
Query OK, 0 rows affected (0.93 sec)

使用插入命令在表格中插入一些记录。

查询如下

mysql> insert into PipeConcatDemo values('Larry');
Query OK, 1 row affected (0.18 sec)
mysql> insert into PipeConcatDemo values('John');
Query OK, 1 row affected (0.15 sec)
mysql> insert into PipeConcatDemo values('Maxwell');
Query OK, 1 row affected (0.23 sec)
mysql> insert into PipeConcatDemo values('Bob');
Query OK, 1 row affected (0.17 sec)

现在,你可以使用 select 语句显示表格中的所有记录。

查询如下

mysql> select *from PipeConcatDemo;

输出如下

+---------+
| Name    |
+---------+
| Larry   |
| John    |
| Maxwell |
| Bob     |
+---------+
4 rows in set (0.00 sec)

现在,在拼接之前,运行以下查询将 sql_mode 更改为 PIPES_AS_CONCAT

mysql> set sql_mode=PIPES_AS_CONCAT;
Query OK, 0 rows affected (0.00 sec)

你现在可以用 || 进行拼接

mysql> select 'Good Morning !!! ' || Name AS PipeConcatenationDemo from PipeConcatDemo;

输出如下

+--------------------------+
| PipeConcatenationDemo    |
+--------------------------+
| Good Morning !!! Larry   |
| Good Morning !!! John    |
| Good Morning !!! Maxwell |
| Good Morning !!! Bob     |
+--------------------------+
4 rows in set (0.00 sec)

更新时间: 30-Jul-2019

112 次浏览

启动你的 职业生涯

完成课程,获得认证资格

开始入门
广告
© . All rights reserved.