MySQL GROUP BY 和 CONCAT() 显示不同的姓和名

mysqlmysqli database更新于 2025/12/12 0:12:17

首先我们创建一个表 −

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

使用 insert 命令在表中插入一些记录 −

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)

相关文章


有用资源