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)
广告