mysql 连接查询和子查询

-- 1.    列出员工表中每个部门的员工数(员工数必须大于 3),和部门名称.
# 先连接
select deptno, count(dname) pe_num from emp natural join dept group by deptno having count(ename) > 3;

-- 2.    找出工资比 jones 多的员工信息。
select * from emp where sal > (select sal from emp where ename = 'jones');

-- 3.    列出所有员工的姓名和其上级的姓名。
select e1.ename ename, e2.ename mgr from emp e1, emp e2 where e1.mgr = e2.empno; 

-- 4.    查询大于30号部门平均工资并且不在30号部门的员工信息和部门名称。
select * from emp natural join dept where sal > (select avg(sal) from emp where deptno = 30) and deptno <> 30;

-- 5.    查询每个月工资总数最少的那个部门的部门编号,部门名称,部门位置。
select deptno, dname, loc, sum(sal) sum from emp natural join dept group by deptno order by sum(sal) limit 1;


-- 6.    查询员工编号为7369的员工姓名和所在部门的部门名称。
select dname, ename from emp natural join dept where empno = 7369;

-- 7.    查询超过其所在部门平均工资的员工信息。
select * from emp natural join (select deptno, avg(sal) avg from emp group by deptno) as new where sal > avg;

-- 8.    查询大于30号部门平均工资并且不在30号部门的员工信息
select * from emp where sal > (select avg(sal) from emp where deptno = 30) and deptno <> 30;

连接查询、子查询、别名

posted @ 2019-11-21 10:38  shiyadongfighting  阅读(55)  评论(0)    收藏  举报