1.基本查询回顾
select sal,job,ename from EMP where (sal>500 or job='MANAGER') and ename like 'J%';
select ename deptno,sal from EMP order by deptno asc,sal desc;
--年薪total=sal*12+comm
select ename,sal*12+ifnull(comm,0) as total
from EMP
order by total desc;
select ename,job
from EMP
where sal=(select max(sal) from EMP);
select * from EMP
where sal>(select avg(sal)from EMP);
select deptno,avg(sal),max(sal)
from EMP
group by deptno;
select deptno,avg(sal)
from EMP
group by deptno
having avg(sal)<2000;
select job,count(*),avg(sal)
from EMP
group by job;
2.多表查询
笛卡尔积:从第一张表中选出第一条记录,和第二张表中的所有记录进行组合;然后从第一张表中取出第二条记录,和第二张表中所有记录进行组合,以此类推得到的结果成为笛卡尔积
select emp.ename,emp.sal,dept.dname
from emp,dept
where emp.deptno=dept.deptno;
--通过deptno 将两张表关联起来
select emp.ename,emp.sal,dept.deptno,dept.dname
from emp,dept
where emp.deptno=dept.deptno and dept.deptno=10;
select e.ename,e.sal,s.grade
from emp e,salgrade s--给两张表分别起了别名
where e.sal between s.losal and s.hisal;
3.自连接
自连接是指在同一张表连接查询
案例:显示员工FORD的上级领导的编号和姓名(mgr是员工领导的编号-empno)
mysql> select empno,ename from emp
-> where emp.empno=(
-> select mgr from emp where ename='FORD');
+--------+-------+
| empno | ename |
+--------+-------+
| 007566 | JONES |
+--------+-------+
mysql> select leader.empno,leader.ename
->from emp leader, emp worker
->where leader.empno = worker.mgr
->and worker.ename='FORD';
+--------+-------+
| empno | ename |
+--------+-------+
| 007566 | JONES |
+--------+-------+
4.子查询
子查询是指嵌入在其他sql语句中的select语句,也叫嵌套查询
4.1单行子查询(返回一行记录)
select * from EMP where deptno =(select deptno from EMP where ename='SMITH');
4.2多行子查询(返回多行记录)
select ename,job,sal,empno from emp
where job in(select distinct job from emp where deptno=10)
and deptno<>10;
select ename, sal, deptno from EMP
where sal > all(select sal from EMP where deptno=30);
select ename, sal, deptno from EMP
where sal > any(select sal from EMP where deptno=30);
4.3多列子查询
多列子查询是指查询返回多个列数据的子查询语句
select ename from emp
where (deptno,job)=(select deptno,job from emp where
ename='SMITH') and ename<>"SMITH';
4.4在from子句中使用子查询
子查询语句出现在from子句中,把一个子查询当做一个临时表使用
select ename, deptno, sal, format(asal,2) from EMP,
(select avg(sal) asal, deptno dt from EMP group by deptno) tmp
where EMP.sal > tmp.asal and EMP.deptno=tmp.dt;
select EMP.ename, EMP.sal, EMP.deptno, ms from EMP,
(select max(sal) ms, deptno from EMP group by deptno) tmp
where EMP.deptno=tmp.deptno and EMP.sal=tmp.ms;
--方法1:多表查询
select DEPT.dname, DEPT.deptno, DEPT.loc,count(*) '部门人数' from EMP, DEPT
where EMP.deptno=DEPT.deptno
group by DEPT.deptno,DEPT.dname,DEPT.loc;
--方法2:使用子查询
-- 1. 对EMP表进行人员统计
select count(*), deptno from EMP group by deptno;
-- 2. 将上面的表看作临时表
select DEPT.deptno, dname, mycnt, loc from DEPT,
(select count(*) mycnt, deptno from EMP group by deptno) tmp
where DEPT.deptno=tmp.deptno;