MySQL GROUP BY和CONCAT()显示不同的名字和姓氏
让我们首先创建一个表-
mysql> create table DemoTable ( FirstName varchar(100), LastName varchar(100) ); mysql> alter table DemoTable add index(FirstName,LastName); Records: 0 Duplicates: 0 Warnings: 0
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('Adam','Smith'); mysql> insert into DemoTable values('Adam','Smith'); mysql> insert into DemoTable values('John','Doe'); mysql> insert into DemoTable values('Carol','Taylor'); mysql> insert into DemoTable values('John','Doe');
使用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)