多表聯合查詢
SQL9
- 笛卡兒積(a*b):將多個表的數據進行一一對應,所得的結果爲多表的笛卡兒積
結果的數量爲多表之積
select * from emp,dept where emp.deptno = dept.deptno
- 等值連接篩選:先做表的笛卡兒積,然後篩選,篩選條件爲等值篩選
可以在select 子句中使用字段獲取數據,但是效率較低
如果是公共字段,必須聲明表名 - 不等值連接
select * from emp as e,salgrade as s where e.sal>=s.losal and e.sal<=s.hisal
- 自連接
查詢員工的姓名、工作、薪資、及上級領導姓名
select e1.ename,e1.job,e1.sal,e2.ename from emp e1,emp e2 where e1.mgr = e2.empno
注:自己與自己做笛卡兒積
- 外連接:
左外連接:可以看到左表爲空的內容
select * from emp e,dept d where e.deptno=d.deptno(+)
右外連接:可以看到右表爲空的內容
select * from emp e,dept d where e.deptno(+)=d.deptno
SQL99
-
笛卡兒積:使用 cross 和 join 關鍵字
select 內容 from 表名 cross join 表名
select * from emp cross join dept -
篩選
- 自然連接:使用關鍵字natural join
- 使用:
select * from emp natural join dept
- 特點:底層爲笛卡兒積,然後按照同名同值字段自動進行篩選
- 缺點:如果想按照字段名不同,但是值相同進行篩選怎麼辦
- 如果只想按照部分字段篩選怎麼辦
- 解決1:使用using關鍵字
作用:指明使用指定字段對聯合查詢結果進行等值篩選
注意:指定字段必須是兩表同名同值字段
使用:select * from emp inner join dept using (deptno)
- 解決1:使用using關鍵字
- 解決2:使用on關鍵字進行自定義連接條件篩選(等值、不等值篩選)
注:普通篩選條件使用where進行篩選,不要使用on 。好處,sql語句的閱讀行
使用:select 內容 from 表名 inner join dept on emp.deptno=dept.deptno
- 如果只想按照部分字段篩選怎麼辦
- 使用:
- 自然連接:使用關鍵字natural join
-
外連接:
- 左外連接
select * from emp left outer join dept on emp.deptno = dept.deptno - 右外連接
select * from emp right outer join dept emp.deptno=dept.deptno - 全外連接
select * from emp full outer join dept emp.deptno = dept.deptno
- 左外連接
-
自連接:
查詢員工及其上級領導姓名
select * from emp e1 inner join emp e2 on e1.msr=m2.empno
SQL92實現:查詢員工信息及部門名稱及所在城市名稱
特點:易於書寫、難於閱讀
使用:
select * from emp e,dept d,city c where (e.deptno=d.deptno and d.loc=c.cid and sal>2000) or (e.deptno=d.deptno and d.loc=c.cid and comm is not null)
SQL99實現:查詢員工信息及部門名稱及所在城市名稱
特點:難於書寫,易於閱讀
使用:
select * from emp e inner join dept d on e.deptno = d.deptno
inner join city c on d.loc = c.cid
where sal>2000 or comm is not null
子查詢:
使用時機:當查詢的篩選條件不明確時,考慮使用子查詢
- 單行子查詢
- 多行子查詢
單行子查詢:
- 使用時機:篩選條件不明確,查詢結果僅有一個 數據
- 注:where語句中允許出現查詢語句,該查詢語句被稱爲子查詢
- 使用:
select * from emp where sal > (select sal from emp where ename='CLARK')
多行子查詢:
- 使用動機,子查詢結果只有一個字段,但是有n個值,考慮使用多行查詢
- 關鍵字:any 任意 、all 所有 、in 任意存在,相當於=any
- 使用:
select * from emp where sal > any (select sal from emp where job='CLERK')