當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


MySQL CONCAT_WS方法用法及代碼示例

MySQL 的 CONCAT_WS(~) 方法使用指定的分隔符連接輸入字符串。

參數

1. separator | string

要在要連接的字符串之間添加的分隔符。

2. str1 | string

與其他字符串輸入連接的字符串。

3. str2 | string

與其他字符串輸入連接的字符串。可以提供任意數量的字符串輸入。

返回值

在字符串輸入之間添加分隔符的串聯字符串。

例子

考慮下表有關一些學生的信息:

student_id

名稱

名字

day_enrolled

年齡

用戶名

1

Sky

Towner

2015-12-03

17

stowner1

2

Ben

Davis

2016-04-20

19

bdavis2

3

Travis

Apple

2018-08-14

18

tapple3

4

Arthur

David

2016-04-01

16

adavid4

5

Benjamin

Town

2014-01-01

17

btown5

可以使用此處的代碼創建上述示例表。

基本用法

要將 fnamelname 連接起來,並在其間添加 '*'

SELECT CONCAT_WS('*', fname, lname)
FROM students;



+------------------------------+
| CONCAT_WS('*', fname, lname) |
+------------------------------+
| Sky*Towner                   |
| Ben*Davis                    |
| Travis*Apple                 |
| Arthur*David                 |
| Benjamin*Town                |
+------------------------------+

要使用 AS 為結果列提供別名:

SELECT CONCAT_WS(' ', fname, lname) AS "Full Name"
FROM students;



+---------------+
| Full Name     |
+---------------+
| Sky Towner    |
| Ben Davis     |
| Travis Apple  |
| Arthur David  |
| Benjamin Town |
+---------------+

數字參數

數字參數自動轉換為字符串:

SELECT CONCAT_WS(' ', fname, 'is', age, 'years old.') AS "Sentence"
FROM students;



+---------------------------+
| Sentence                  |
+---------------------------+
| Sky is 17 years old.      |
| Ben is 19 years old.      |
| Travis is 18 years old.   |
| Arthur is 16 years old.   |
| Benjamin is 17 years old. |
+---------------------------+

空參數

NULL 輸入字符串被跳過:

SELECT CONCAT_WS('-', 'Welcome', NULL, 'to', 'SkyTowner!');



+-----------------------------------------------------+
| CONCAT_WS('-', 'Welcome', NULL, 'to', 'SkyTowner!') |
+-----------------------------------------------------+
| Welcome-to-SkyTowner!                               |
+-----------------------------------------------------+

NULL 分隔符返回 NULL

SELECT CONCAT_WS(NULL, 'Welcome', 'to', 'SkyTowner!');



+------------------------------------------------+
| CONCAT_WS(NULL, 'Welcome', 'to', 'SkyTowner!') |
+------------------------------------------------+
| NULL                                           |
+------------------------------------------------+

相關用法


注:本文由純淨天空篩選整理自Arthur Yanagisawa大神的英文原創作品 MySQL | CONCAT_WS method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。