連接查詢,會產生笛卡爾積,有時會降低運行效率。
--等值連接
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