select ename from emp where (sal > 500 OR job = 'MANGER') and substring(ename,1,1) = 'J';
select * from emp order by deptno asc,sal desc;
select sal*12+ifnull(comm,0) as sum from emp order by sum desc;
select * from emp where sal = (select max(sal) from emp);
select * from emp where sal > (select avg(sal) from emp);
select deptno,format(max(sal),2) 最高 , format(avg(sal),2) 平均 from emp group by deptno;
select deptno,avg(sal) 平均 from emp group by deptno having 平均 > 2000;
select job,count(*) 人数,avg(sal) 平均工资 from emp group by job;
两张表进行笛卡尔积。即用第一张表的一条数据和第二张表的所有数据进行组合。
select emp.ename,sal,dname from emp,dept where emp.deptno=dept.deptno;
select ename,sal,grade from emp,salgrade where sal between losal and hisal;
select * from salgrade as t1,salgrade as t2;
//子查询
select mgr from emp where ename = 'FORD';
select ename,emptno from emp where empno = (select mgr from emp where ename = 'FORD');
//自连接
select * from emp e1,emp e2 where e1.name='FORD' and e1.mgr=e2.empno;
嵌入在其他sql语句中的select语句,也叫嵌套查询
select dptno from emp where ename = 'SMITH';
select * from emp where deptno=(select dptno from emp where ename = 'SMITH')
select ename,job,sal,deptno from emp where job in (select distinct job from emp where deptno=10) and deptno <> 10;
还要员工的部门名字:
select * from (select ename,job,sal,deptno from emp where job in (select distinct job from emp where deptno=10) and deptno <> 10) as tmp , dept where dept.deptno=tmp.deptno;
select * from emp where sal > (select max(sal) from emp where deptno=30);
select * from emp where sal > all(select distinct sal from emp where deptno=30);
select * from emp where sal > any(select distinct sal from emp where deptno=30);
select * from emp where (dept,job) in (select deptno,job from emp where ename='SMITH') and ename <> 'SMITH';
//1.每个部门的平均工资
select deptno,avg(sal) from emp group by deptno;
//2.进行笛卡尔积
select * from emp,(select deptno,avg(sal) from emp group by deptno) as tmp;
//3.筛选正确的部门
select * from emp,(select deptno,avg(sal) from emp group by deptno) as tmp where emp.deptno = tmp.deptno;
//4.单表查询
select * from emp,(select deptno,avg(sal) myavg from emp group by deptno) as tmp where emp.deptno = tmp.deptno and emp.sal > tmp.myavg;
查看这一些人的办公地点:
1.上面的查询结果和dept表进行笛卡尔积
2.筛选合适的行
3.按条件得到要求的
//1.每个部门的最高工资
select deptno,max(sal) from emp group by deptno;
//2.和emp表笛卡尔积,找到谁是最高的那个人
select ename,sal,t1.deptno,mymax from emp t1, (select deptno,max(sal) mymax from emp group by deptno) t2 where t1.deptno = t2.deptno and t1.sal = t2.mymax;
//3.
//各部门人员数量
select deptno,count(*) dept_num from emp group by deptno;
//跟dept表进行笛卡尔积
select t1.dname,t1.loc,t2.dept_num,t1.deptno from dept t1,(select deptno,count(*) dept_num from emp group by deptno) t2 where t1.deptno=t2.deptno;
多表查询的本质:将多表转换成单表。
该操作符用于取得两个结果集的并集,当使用该操作符时,会自动去掉结果集中的重复行(自动去重)。要拼接的时候要满足两个列一致,否则不能拼。
select * from emp where job = 'MANNAGER' union select * from emp where job = 'MANAGER';
该操作符不会对满足多个条件的数据进行去重,而是保留。