在 MySQL 中合併兩列?


要合併兩列,請在 MySQL 中使用 CONCAT() 函式。語法如下 −

select CONCAT(yourColumnName1, ' ',yourColumnName2) as anyVariableName from yourTableName;

為了理解上述概念,讓我們建立一個表。建立表的查詢如下 −

mysql> create table concatenateTwoColumnsDemo
   −> (
   −> StudentId int,
   −> StudentName varchar(200),
   −> StudentAge int
   −> );
Query OK, 0 rows affected (1.06 sec)

現在,可以在表中插入一些記錄。插入記錄的查詢如下 −

mysql> insert into concatenateTwoColumnsDemo values(1,'Sam',21);
Query OK, 1 row affected (0.18 sec)

mysql> insert into concatenateTwoColumnsDemo values(2,'David',24);
Query OK, 1 row affected (0.17 sec)

mysql> insert into concatenateTwoColumnsDemo values(3,'Carol',22);
Query OK, 1 row affected (0.13 sec)

mysql> insert into concatenateTwoColumnsDemo values(4,'Johnson',19);
Query OK, 1 row affected (0.17 sec)

在 select 語句的幫助下從表中顯示所有記錄。查詢如下 −

mysql> select *from concatenateTwoColumnsDemo;

以下是輸出 −

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
|         1 | Sam         |         21 |
|         2 | David       |         24 |
|         3 | Carol       |         22 |
|         4 | Johnson     |         19 |
+-----------+-------------+------------+
4 rows in set (0.00 sec)

實施 CONCAT() 函式以合併兩列。在此,我們要合併 StudentName 和 StudentAge 列。查詢如下 −

mysql> select CONCAT(StudentName, ' ',StudentAge) as NameAndAgeColumn from concatenateTwoColumnsDemo;

以下是顯示合併列的輸出 −

+------------------+
| NameAndAgeColumn |
+------------------+
| Sam 21           |
| David 24         |
| Carol 22         |
| Johnson 19       |
+------------------+
4 rows in set (0.00 sec)

更新於: 30-Jul-2019

8K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告