数据库修仙之路3

1.表连接  

--查询员工信息以及所在的部门信息

--数据: ename,dname

--来源:emp,dept

select  * from emp,dept;--笛卡尔积 两个表中数据相乘  一共48

select  * from emp,dept where emp.deptno=dept.deptno; --内连接  满足条件的数据显示

select  * from emp,dept where emp.deptno=dept.deptno(+); --所有员工及所在的部门信息  12条数据后面拼接对应的员工信息

select  * from emp,dept where emp.deptno(+)=dept.deptno;

--92语法  99语法

--笛卡尔积

select * from emp,dept;

--等值连接 ,链接条件的类型相同就可以写

select * from emp,dept where emp.deptno=dept.deptno;

select * from emp,dept where emp.ename=dept.ename;

--30部门的员工名字和部门名字,在链表查询的时候,如果有相同字段使用的时候,必须指定字段来自的表

--30部门的员工名字和部门名字

select ename,dname from emp,dept where emp.deptno=30 and emp.deptno=dept.deptno;

select ename,dname from emp e,dept d where e.deptno=30 and e.deptno=d.deptno;

select ename, dname, e.deptno

  from emp e, dept d

 where e.deptno = 30

   and e.deptno = d.deptno;   ---先关联后过滤,不推荐,效率低

--先过滤后关联

select * from emp where deptno=30;

select * from dept where deptno=30;

select * from (select * from emp where deptno=30),(select * from dept where deptno=30);  --先过滤后关联

--非等值连接

--查询员工信息以及薪资等级

-- 2500的薪资等级

select * from salgrade where 2500 between losal and hisal;

select*from emp ,salgrade  where sal between losal and hisal;

select * from emp e,salgrade s where e.sal between s.losal and s.hisal;

2.表连接:

--查询员工的信息,所在部门信息,以及薪资等级(注意:涉及到了三张表)

select * from emp,dept,salgrade where emp.deptno=dept.deptno and  sal between losal and hisal;

--自连接和外连接(外连接就是两个表相连)

select * from emp,dept where emp.deptno=dept.deptno;

--主表 主表中的所有数据全部显示(比如说emp表和dept表相连,主表中的数据全部

--显现,dept作为主表的话,emp.deptno(+)=dept.deptno)

--左连接|右连接,看主表在,的左边还是右边(外连接分为左连接和右连接)

select * from emp,dept where emp.deptno(+)=dept.deptno; --外连接:dept主表    右连接

select * from dept,emp where emp.deptno(+)=dept.deptno; --外连接:左连接(主表在逗号的左边)

select * from dept,emp where emp.deptno=dept.deptno(+);

--自连接  自己和自己连接

--打印所有有上级的员工的员工信息和其上级员工信息

select * from emp e , emp mgr where e.mgr=mgr.empno;

--所有员工的员工信息及其领导信息

select * from emp e , emp mgr where e.mgr=mgr.empno(+);

:

--查询所有有上级的员工的信息及上级信息  假设e1是员工表  e2是上级表

select * from emp e1,emp e2 where e1.mgr=e2.empno;

--查询所有员工的信息及上级信息  假设e1是员工表  e2是上级表

--需求:想要期中的某张表中所有的数据全部展示,无论是否满足等值连接条件 --外链接

--外链接:确认主表(主表中的内容会全部展示)   +对面的表为主表,+所在的表为从表

--左外连接   主表在,的左边叫做左连接

--右连接     主表在,的右边叫做右连接

--自连接     特殊的连接,自己连接自己  也可以自外链接

select * from emp e2,emp e1 where e1.mgr=e2.empno(+); --右连接

select * from emp e1,emp e2 where e1.mgr=e2.empno(+); --左连接

select * from emp e1,emp e2 where e1.mgr=e2.empno; --自连接

--找出所有有员工的部门名称以及员工数

select deptno,count(1) from emp group by deptno;

select dname, c

  from dept d, (select deptno, count(1) c from emp group by deptno) e

 where d.deptno = e.deptno;

--找出 所有部门的员工数 及部门名称

select dname, nvl(c,0)

  from dept d, (select deptno, count(1) c from emp group by deptno) e

 where d.deptno = e.deptno(+);  --左链接

猜你喜欢

转载自www.cnblogs.com/greyrhinoceros-1998/p/10876733.html