--笛卡爾集select empno,ename, 員工表.deptno, 部門表.deptno, dname from 部門表, 員工表; --添加合適的條件,可以避免笛卡爾集,從而得到正確的多表查詢記錄select empno,ename, 員工表.deptno, 部門表.deptno, dna ...
--笛卡爾集
select empno,ename, 員工表.deptno, 部門表.deptno, dname
from 部門表, 員工表;
--添加合適的條件,可以避免笛卡爾集,從而得到正確的多表查詢記錄
select empno,ename, 員工表.deptno, 部門表.deptno, dname
from 部門表, 員工表
where 部門表.deptno = 員工表.deptno;
--查詢員工信息,要求顯示:員工號,姓名,職位,部門名稱
--等值連接
select empno,ename,job,dname from emp, dept where emp.deptno = dept.deptno;
--多個條件的等值連接,使用AND操作符
select e.empno,e.ename,e.job,d.dname,d.deptno from emp e, dept d where e.deptno = d.deptno and e.deptno=10;
--顯示所有員工的員工號、姓名、工資及其工資的等級。
select * from salgrade;
--非等值連接
select e.empno, e.ename, e.sal, s.grade from emp e, salgrade s where e.sal between losal and hisal;
--按部門統計員工的人數,要求顯示:部門號,部門名稱,人數
select d.deptno,d.dname,count(e.empno) from dept d, emp e where d.deptno = e.deptno group by d.deptno, d.dname;
select * from dept;
select * from emp where deptno=40;
--外連接
select d.deptno,d.dname,count(e.empno) from dept d, emp e where d.deptno = e.deptno(+) group by d.deptno, d.dname;
--自連接
--查詢所有員工的姓名和直屬上級的姓名
select e.ename,m.ename
from emp e, emp m
where e.mgr = m.empno;
--驗證 ford-->jones
select * from emp;
--cross join
select d.dname, e.ename, d.deptno, e.deptno from dept d cross join emp e;
select count(*) from emp;
select count(*) from dept;
--natural join
--查詢員工名、工資以及所在部門名稱
select e.ename, e.sal, d.dname from dept d natural join emp e;
--內連接
--using子句
select e.ename,e.sal, d.dname from dept d join emp e using(deptno);
--通過on指定內連接的條件
select e.ename,e.sal, d.dname from dept d join emp e on d.deptno = e.deptno;
--內連接的關鍵字inner join, inner通常省略
select e.ename,e.sal, d.dname from dept d inner join emp e on d.deptno = e.deptno;
--左外連接
select e.ename,e.sal, d.dname from dept d left join emp e on d.deptno = e.deptno;
--右連接
select e.ename,e.sal, d.dname from dept d right join emp e on d.deptno = e.deptno;
--完全連接
select e.ename,e.sal, d.dname from dept d full join emp e on d.deptno = e.deptno;
--emp01
create table emp01
as
select * from emp where deptno in(10,20);
--emp02
create table emp02
as
select * from emp where deptno in(20,30);
--合併顯示emp01表和emp02表所有雇員的部門編號、員工號、員工姓名。
--10號部門有3個、20號部門有5個、
select * from emp01;
--30號部門有6個、
select * from emp02;
--union 14個記錄
select deptno, empno, ename from emp01
union
select deptno, empno, ename from emp02;
--union all
--通過部門號進行排序
select deptno, empno, ename from emp01
union all
select deptno, empno, ename from emp02
order by deptno;
--通過列值進行排序,1代表第一列
select deptno, empno, ename from emp01
union all
select deptno, empno, ename from emp02
order by 1;
--intersect
select deptno, empno, ename from emp01
intersect
select deptno, empno, ename from emp02;
--minus
select deptno, empno, ename from emp01
minus
select deptno, empno, ename from emp02;