在 MySQL 中連線字串到 SELECT *?


使用 MySQL 中的 CONCAT() 函式連線字串,如下面的語法所示

SELECT
CONCAT(yourColumnName1,’anyConcatenationString’),CONCAT(yourColumnName2,’anyC
oncatenationString’),....N from yourTableName;

為了理解上述語法,我們首先建立一個表。建立表的查詢如下

mysql> create table selectConcat
-> (
-> StudentId int,
-> StudentName varchar(100),
-> StudentAge int
-> );
Query OK, 0 rows affected (1.32 sec)

使用插入命令在表中插入一些記錄。查詢如下

mysql> insert into selectConcat values(1,'Carol',23);
Query OK, 1 row affected (0.19 sec)

mysql> insert into selectConcat values(2,'John',24);
Query OK, 1 row affected (0.25 sec)

mysql> insert into selectConcat values(3,'Adam',25);
Query OK, 1 row affected (0.14 sec)

mysql> insert into selectConcat values(4,'Bob',21);
Query OK, 1 row affected (0.20 sec)

mysql> insert into selectConcat values(5,'Sam',22);
Query OK, 1 row affected (0.16 sec)

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

mysql> select *from selectConcat;

以下是輸出

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
| 1         | Carol       | 23         |
| 2         | John        | 24         |
| 3         | Adam        | 25         |
| 4         | Bob         | 21         |
| 5         | Sam         | 22         |
+-----------+-------------+------------+
5 rows in set (0.00 sec)

連線 select 語句中的欄位。查詢如下

mysql> select concat(StudentId,' as an Id'),concat(StudentName,' as a Name') from selectConcat;

以下是輸出

+-------------------------------+----------------------------------+
| concat(StudentId,' as an Id') | concat(StudentName,' as a Name') |
+-------------------------------+----------------------------------+
| 1 as an Id                    | Carol as a Name                  |
| 2 as an Id                    | John as a Name                   |
| 3 as an Id                    | Adam as a Name                   |
| 4 as an Id                    | Bob as a Name                    |
| 5 as an Id                    | Sam as a Name                    |
+-------------------------------+----------------------------------+
5 rows in set (0.00 sec)

更新日期:29-Jun-2020

160 檢視次數

開啟您的 職業 生涯

完成課程並獲得認證

開始
廣告