您可以使用子查询从Employee表中获取最高和第二最高薪水。
让我们首先创建一个表。创建表的查询如下-
mysql> create table EmployeeMaxAndSecondMaxSalary -> ( -> EmployeeId int, -> Employeename varchar(20), -> EmployeeSalary int -> );
使用插入命令在表中插入一些记录-
mysql> insert into EmployeeMaxAndSecondMaxSalary values(1,'John',34566); mysql> insert into EmployeeMaxAndSecondMaxSalary values(2,'Bob',56789); mysql> insert into EmployeeMaxAndSecondMaxSalary values(3,'Carol',44560); mysql> insert into EmployeeMaxAndSecondMaxSalary values(4,'Sam',76456); mysql> insert into EmployeeMaxAndSecondMaxSalary values(5,'Mike',65566); mysql> insert into EmployeeMaxAndSecondMaxSalary values(6,'David',89990); mysql> insert into EmployeeMaxAndSecondMaxSalary values(7,'James',68789); mysql> insert into EmployeeMaxAndSecondMaxSalary values(8,'Robert',76543);
使用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)