如何使用 MySQL GROUP BY 从特定公司中获取员工姓名?


我们先创建一个表 -

mysql> create table DemoTable642(
   EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,EmployeeName archar(100), EmployeeCompanyNamevarchar(100)
);
Query OK, 0 rows affected (0.81 sec)

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

mysql> insert into DemoTable642(EmployeeName,EmployeeCompanyName) values('John','Google');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable642(EmployeeName,EmployeeCompanyName) values('Carol','Microsoft');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable642(EmployeeName,EmployeeCompanyName) values('John','Amazon');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable642(EmployeeName,EmployeeCompanyName) values('Carol','Google');
Query OK, 1 row affected (0.37 sec)
mysql> insert into DemoTable642(EmployeeName,EmployeeCompanyName) values('John','Flipkart');
Query OK, 1 row affected (0.14 sec)

使用 select 语句显示表中的所有记录 -

mysql> select *from DemoTable642;

这将产生以下输出 -

+------------+--------------+---------------------+
| EmployeeId | EmployeeName | EmployeeCompanyName |
+------------+--------------+---------------------+
| 1          | John         | Google              |
| 2          | Carol        | Microsoft           |
| 3          | John         | Amazon              |
| 4          | Carol        | Google              |
| 5          | John         | Flipkart            |
+------------+--------------+---------------------+
5 rows in set (0.00 sec)

以下是从特定公司获取员工姓名的查询 -

mysql> select EmployeeName from DemoTable642
   where EmployeeCompanyName="Google"
   group by EmployeeName;

这将产生以下输出 -

+--------------+
| EmployeeName |
+--------------+
| John         |
| Carol        |
+--------------+
2 rows in set (0.00 sec)

更新时间: 2019 年 8 月 23 日

128 次浏览

开启您的 职业生涯

完成课程,获得认证

立即开始
广告