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.