連接查詢

連接查詢,會產生笛卡爾積,有時會降低運行效率。


--等值連接
select * from emp e,dept d
where e.deptno=d.deptno


--查詢ACCOUNTING部門下有哪些員工


--使用連接查詢
select  * from emp e,dept d
where e.deptno=d.deptno and d.dname='ACCOUNTING'


--使用嵌套子循環
select * from emp where deptno=(select deptno from dept where dname='ACCOUNTING')


--查詢所有員工的工資等級
select * from emp e,salgrade s
where e.sal between s.losal and s.hisal


--查詢各個工資等級的人數
select s.grade as 工資等級,
       count(s.grade) as 該等級人數 from emp e,salgrade s
where e.sal between s.losal and s.hisal
group by s.grade


--查詢每個部門每種工資等級的人數
select d.dname as 部門名稱,
       s.grade as 工資等級,
       count(*) as  人數 from emp e, dept d, salgrade s
where e.deptno=d.deptno and e.sal between s.losal and s.hisal
group by d.dname,s.grade
order by d.dname,s.grade




--外連接 左外連接  右外連接
         --左外連接  以emp爲左表
select * from emp e
left join dept d on e.deptno=d.deptno
         --左外連接  以dept爲左表
select * from dept d
left join emp e on e.deptno=d.deptno
--什麼時候用外連接
select * from dept d
left join emp e on e.deptno=d.deptno
where e.deptno is null




--自連接
select * from emp e,emp e1
where e.mgr=e1.empno


--顯示各個經理帶了幾個員工
select mgr, count(*) from emp
where mgr is not null
group   by mgr


--顯示各個經理名字
select e1.ename from emp e,emp e1
where e.mgr=e1.empno and e1.mgr is not null
group by e1.ename


--顯示不重複元素
select distinct job from emp


發佈了42 篇原創文章 · 獲贊 14 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章