Day3_查询语句进阶
常用查询语句
-- 查询月薪最高的员工姓名和月薪
-- any() 其中一个为Ture,整个为True;all() 所有都为True才为True
select ename,sal from tb_emp where sal = (select max(sal) from tb_emp);
select ename,sal from tb_emp where sal >= all(select sal from tb_emp);
-- 查询员工的姓名和年薪((月薪+补贴)*13)
select ename ,(sal+ ifnull(comm,0))*13 as year_sal from tb_emp order by year_sal desc;
-- 查询有员工的部门的编号和人数
select dno,count(*) as total from tb_emp group by(dno);
-- 查询所有部门的名称和人数
select dname,ifnull(total,0) as total from tb_dept left outer join (
select dno,count(*) as total from tb_emp group by(dno)) tb_temp on tb_dept.dno =tb_temp.dno;
-- 查询月薪最高的员工(Boss除外)的姓名和月薪
select ename ,sal from tb_emp where sal =
(select max(sal) from tb_emp where mgr is not null);
-- 查月薪排第2名的员工的姓名和月薪
select ename,sal from
(select @a := @a + 1 as row_num ,ename,sal from tb_emp,(select @a:=0) t1 order by sal desc) t2 where row_num =2;
-- 查询月薪超过平均月薪的员工的姓名和月薪
select ename,sal from tb_emp where sal >(select avg(sal) from tb_emp);
-- 查询月薪超过其所在部门平均月薪的员工的姓名、部门编号和月薪
select ename ,dno,sal from tb_emp inner join(
select dno as dept_num ,avg(sal) as avg_sal from tb_emp group by dno) tb_temp on dno=dept_num where sal >avg_sal ;
-- 查询部门中月薪最高的人姓名、月薪和所在部门名称
select ename ,sal,dname from tb_dept join
tb_emp on tb_dept.dno = tb_emp.dno join
(select dno as dept_num ,max(sal) as max_sal from tb_emp group by dno) tb_temp on tb_emp.dno = dept_num where sal = max_sal;
-- 查询主管的姓名和职位
-- 尽量少用in/not in 运算,尽量少用distinct操作
-- 可以使用存在性判断(exsits/not exsits)代替集合运算