-- 内连接:
-- 显示员工姓名、工资和公司所在地
select e.ename, e.sal, d.dname from emp e,dept d; -- 笛卡尔积
select e.ename, e.sal, d.dname from emp e join dept d; -- oracle语法错误,没有笛卡尔积;mysql 没有语法错误
select e.ename, e.sal, d.dname from emp e, dept d where e.deptno = d.deptno;
select e.ename, e.sal, d.dname from emp e join dept d on e.deptno=d.deptno;
-- 显示部门号为10的员工姓名、工资、部门名称
select d.dname, e.ename, e.sal from emp e, dept d where d.deptno = e.deptno and e.deptno = 10;
select d.dname, e.ename, e.sal from emp e join dept d on d.deptno = e.deptno where e.deptno = 10;
-- 显示姓名、工资、工资的级别(on 后面不仅仅可以加 ... = ... ,还可以是 between ....and ...)
select e.ename, e.sal, s.grade from emp e, salgrade s where e.sal between s.losal and s.hisal;
select e.ename, e.sal, s.grade from emp e join salgrade s on e.sal between s.losal and s.hisal;
-- 显示姓名、工资、部门名称,并按部门号排序
select e.ename, e.sal, d.dname from emp e join dept d on e.deptno = d.deptno order by e.deptno desc;
-- 自关联
-- 查询FORD上级领导名字
select e.ename, e.sal, e.job, e.sal, o.ename from emp e join emp o on e.mgr = o.empno where e.ename = 'FORD';
-- 单行子查询:
-- 查询和 SMITH 同一部门的所有员工
select * from emp e where e.deptno = (select deptno from emp where ename = 'SMITH');
-- 查询工资大于 30号部门所有员工工资的员工
select * from emp o where o.sal > (select max(sal) from emp e where e.deptno=30);
-- 多列子查询:
-- 查询与 SMITH 的部门和岗位完全相同的员工
select * from emp e where (e.deptno, e.job) = (select o.deptno, o.job from emp o where o.ename = 'SMITH');
-- 高于自己部门平均工资的员工信息
select * from emp o join (select deptno, avg(sal) avg_sal from emp group by deptno) e on e.deptno=o.deptno where sal>avg_sal;
-- 修改SIMTH的岗位、工资、补助和scott的一样
update emp set (job, sal, comm) = (select job, sal, comm from emp where ename='SCOTT') where ename='SMITH'; -- mysql错误
-- 多行子查询
insert into bonus values(1,2,3,4);
insert into bonus select * from bonus; -- oracle、mysql都支持
insert into bonus(ename, job) select ename, job from bonus;
create table test(id, name, sal, job, deptno) as select empno, ename, sal, job, deptno from emp; -- mysql 错误,用查询结果创建一个新表:
-- 合并查询
-- union, union all, intersect, minus
-- union 并集,去掉重复行
select * from emp where sal>2500 union select * from emp where job='MANAGER';
-- union all 并集,不去掉重复行
select * from emp where sal>2500 union all select * from emp where job='MANAGER';
-- intersect 交集
select * from emp where sal>2500 intersect select * from emp where job='MANAGER';
-- minus 差集,存在于第一个集合中,且不存在于第二个集合中
select * from emp where sal>2500 minus select * from emp where job='MANAGER'; -- mysql 错误
select * from emp where job='MANAGER' minus select * from emp where sal>2500; -- mysql 错误
-- 差集图示: