如何将 MySQL 中的几行记录合并在一起?


为此,使用 CASE WHEN 概念。我们先创建一个表 -

mysql> create table demo68
−> (
−> id int not null auto_increment primary key,
−> company_name varchar(50),
−> employee_name varchar(50),
−> country_name varchar(50)
−> );
Query OK, 0 rows affected (1.86 sec)

使用 insert 命令向表中插入一些记录 -

mysql> insert into demo68(company_name,employee_name,country_name)
values('Google','John','US');
Query OK, 1 row affected (0.29 sec)

mysql> insert into demo68(company_name,employee_name,country_name)
values('Google','Bob','UK');
Query OK, 1 row affected (0.10 sec)

mysql> insert into demo68(company_name,employee_name,country_name)
values('Google','David','AUS');
Query OK, 1 row affected (0.08 sec)

使用 select 语句从表中显示记录 -

mysql> select *from demo68;

将产生以下输出 -

+----+--------------+---------------+--------------+
| id | company_name | employee_name | country_name |
+----+--------------+---------------+--------------+
| 1  | Google       | John          | US           |
| 2  | Google       | Bob           | UK           |
| 3  | Google       | David         | AUS          |
+----+--------------+---------------+--------------+
3 rows in set (0.00 sec)

以下是将 MySQL 中的几行记录合并在一起的查询 -

mysql> select
−> company_name,
−> max(case when country_name= 'US' then employee_name end) as
US_Employee_Name,
−> max(case when country_name= 'UK' then employee_name end) as
UK_Employee_Name,
−> max(case when country_name= 'AUS' then employee_name end) as
AUS_Employee_Name
−> from demo68
−> group by company_name;

将产生以下输出 -

+--------------+------------------+------------------+-------------------+
| company_name | US_Employee_Name | UK_Employee_Name | AUS_Employee_Name |
+--------------+------------------+------------------+-------------------+
| Google       | John             | Bob              | David             |
+--------------+------------------+------------------+-------------------+
1 row in set (0.05 sec)

更新于: 20-11-2020

79 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告