利用子查询,求出 MySQL 员工表中的最大和第二大工资?
使用子查询可以从员工表中获得最大和第二大工资。
首先让我们创建一个表。创建表的查询如下 -
mysql> create table EmployeeMaxAndSecondMaxSalary -> ( -> EmployeeId int, -> Employeename varchar(20), -> EmployeeSalary int -> ); Query OK, 0 rows affected (0.88 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into EmployeeMaxAndSecondMaxSalary values(1,'John',34566); Query OK, 1 row affected (0.20 sec) mysql> insert into EmployeeMaxAndSecondMaxSalary values(2,'Bob',56789); Query OK, 1 row affected (0.17 sec) mysql> insert into EmployeeMaxAndSecondMaxSalary values(3,'Carol',44560); Query OK, 1 row affected (0.26 sec) mysql> insert into EmployeeMaxAndSecondMaxSalary values(4,'Sam',76456); Query OK, 1 row affected (0.29 sec) mysql> insert into EmployeeMaxAndSecondMaxSalary values(5,'Mike',65566); Query OK, 1 row affected (0.14 sec) mysql> insert into EmployeeMaxAndSecondMaxSalary values(6,'David',89990); Query OK, 1 row affected (0.19 sec) mysql> insert into EmployeeMaxAndSecondMaxSalary values(7,'James',68789); Query OK, 1 row affected (0.12 sec) mysql> insert into EmployeeMaxAndSecondMaxSalary values(8,'Robert',76543); Query OK, 1 row affected (0.13 sec)
使用 select 语句显示表中的所有记录。查询如下 -
mysql> select *from EmployeeMaxAndSecondMaxSalary;
以下为输出。
+------------+--------------+----------------+ | EmployeeId | Employeename | EmployeeSalary | +------------+--------------+----------------+ | 1 | John | 34566 | | 2 | Bob | 56789 | | 3 | Carol | 44560 | | 4 | Sam | 76456 | | 5 | Mike | 65566 | | 6 | David | 89990 | | 7 | James | 68789 | | 8 | Robert | 76543 | +------------+--------------+----------------+ 8 rows in set (0.00 sec)
使用子查询获取最大和第二大工资的查询 -
mysql> select (select max(EmployeeSalary) from EmployeeMaxAndSecondMaxSalary) MaximumSalary, -> (select max(EmployeeSalary) from EmployeeMaxAndSecondMaxSalary -> where EmployeeSalary not in(select max(EmployeeSalary) from EmployeeMaxAndSecondMaxSalary)) as SecondMaximumSalary;
以下输出显示了两项最高工资 -
+---------------+---------------------+ | MaximumSalary | SecondMaximumSalary | +---------------+---------------------+ | 89990 | 76543 | +---------------+---------------------+ 1 row in set (0.00 sec)
广告