在 MySQL SELECT 子句中新增/連線文字值?


要在 select 子句中新增/連線文字值,可以使用 concat() 函式。

讓我們建立一個表

mysql> create table ConcatenatingDemo
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserName varchar(20),
   -> UserCountryName varchar(20)
   -> );
Query OK, 0 rows affected (0.82 sec)

現在,你可以使用 insert 命令在表中插入一些記錄。查詢如下 −

mysql> insert into ConcatenatingDemo(UserName,UserCountryName) values('John','US');
Query OK, 1 row affected (0.14 sec)
mysql> insert into ConcatenatingDemo(UserName,UserCountryName) values('Carol','UK');
Query OK, 1 row affected (0.13 sec)
mysql> insert into ConcatenatingDemo(UserName,UserCountryName) values('Bob','AUS');
Query OK, 1 row affected (0.15 sec)
mysql> insert into ConcatenatingDemo(UserName,UserCountryName) values('David','US');
Query OK, 1 row affected (0.29 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下 −

mysql> select *from ConcatenatingDemo;

以下是輸出

+--------+----------+-----------------+
| UserId | UserName | UserCountryName |
+--------+----------+-----------------+
|      1 | John     | US              |
|      2 | Carol    | UK              |
|      3 | Bob      | AUS             |
|      4 | David    | US              |
+--------+----------+-----------------+
4 rows in set (0.00 sec)

這裡有在 SELECT 子句中新增/連線文字值的查詢

mysql> select concat(UserName,' belongs to ( ',UserCountryName,' )') as AddingTextDemo from ConcatenatingDemo;

以下是輸出

+-------------------------+
| AddingTextDemo          |
+-------------------------+
| John belongs to ( US )  |
| Carol belongs to ( UK ) |
| Bob belongs to ( AUS )  |
| David belongs to ( US ) |
+-------------------------+
4 rows in set (0.00 sec)

更新時間:2019 年 7 月 30 日

1K+ 次瀏覽

開啟你的 職業生涯

透過完成本課程獲得認證

入門指南
廣告
© . All rights reserved.