MySQL 使用 GROUP BY 和 CONCAT() 顯示不同的姓和名


我們首先建立一個表 -

mysql> create table DemoTable
(
   FirstName varchar(100),
   LastName varchar(100)
);
Query OK, 0 rows affected (0.92 sec)
mysql> alter table DemoTable add index(FirstName,LastName);
Query OK, 0 rows affected (1.00 sec)
Records: 0 Duplicates: 0 Warnings: 0

使用插入命令在表中插入一些記錄 -

mysql> insert into DemoTable values('Adam','Smith');
Query OK, 1 row affected (0.73 sec)
mysql> insert into DemoTable values('Adam','Smith');
Query OK, 1 row affected (1.17 sec)
mysql> insert into DemoTable values('John','Doe');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Carol','Taylor');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable values('John','Doe');
Query OK, 1 row affected (0.66 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select *from DemoTable;

這將生成以下輸出 -

+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| Adam      | Smith    |
| Adam      | Smith    |
| Carol     | Taylor   |
| John      | Doe      |
| John      | Doe      |
+-----------+----------+
5 rows in set (0.00 sec)

以下查詢用於合併不同的姓和名 -

mysql> select concat(FirstName,' ',LastName) as combinedName from DemoTable
group by LastName,FirstName;

這將生成以下輸出 -

+--------------+
| combinedName |
+--------------+
| Adam Smith   |
| Carol Taylor |
| John Doe     |
+--------------+
3 rows in set (0.00 sec)

更新於: 25-Sep-2019

1K+ 瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告