Employee
表包含所有员工信息,每个员工有其对应的 Id, salary 和 department Id。
+----+-------+--------+--------------+ | Id | Name | Salary | DepartmentId | +----+-------+--------+--------------+ | 1 | Joe | 70000 | 1 | | 2 | Henry | 80000 | 2 | | 3 | Sam | 60000 | 2 | | 4 | Max | 90000 | 1 | +----+-------+--------+--------------+
Department
表包含公司所有部门的信息。
+----+----------+ | Id | Name | +----+----------+ | 1 | IT | | 2 | Sales | +----+----------+
编写一个 SQL 查询,找出每个部门工资最高的员工。例如,根据上述给定的表格,Max 在 IT 部门有最高工资,Henry 在 Sales 部门有最高工资。
+------------+----------+--------+ | Department | Employee | Salary | +------------+----------+--------+ | IT | Max | 90000 | | Sales | Henry | 80000 | +------------+----------+--------+
解:
Select d.name as Department,e.Name as Employee, e.Salary
from Employee as e,Department as d
where e.DepartmentId = d.Id and
e.Salary = (select max(Salary) from Employee as e2 where d.Id = e2.DepartmentId)
记几个问题:
1.表别名的用法,只要打上了表别名,就不再是这个表了。如果前后有两个嵌套形式的select语句,因为是select肯定都要跟from某个表,前面一旦打上了别名,后面跟前面用的就真的不是一个表了。
所以只要用了别名,都要看清作用范围,没有引入第二个select就一直有效,引入了另说。
2.select的嵌套用法:
sql中的两个简单嵌套:
(1)select *from table1 where name1>(select name2 from table2);
(2)select *,(select * from table2)as column_name from table1;
(3)select *form (select name1 from table1 where id>3) as t1;
首先是前两个,最大的区别就在于要提取的那一部分,表里有没有现成的,有现成的就先抽出来,然后在后面用where去控制这个范围,如果没有现成的,那就在一开始的时候select (select)as A from table,在一开始的时候写上有这么个东西。
第三个就是在筛选过一遍的范围里面,再次进行筛选,记得中间那个select用括号套好,后面写上as t