定义:用于查询满足连接条件?和不满足连接条件的记录。
查询emp表记录
SELECT * FROM emp;
empno ename job mgr hiredate sal comm deptno
1 7369 SMITH CLERK 7902 1980/12/17 800.00 20
2 7499 ALLEN SALESMAN 7698 1981/2/20 1600.00 300.00 30
3 7521 WARD SALESMAN 7698 1981/2/22 1250.00 500.00 30
4 7566 JONES MANAGER 7839 1981/4/2 2975.00 20
5 7654 MARTIN SALESMAN 7698 1981/9/28 1250.00 1400.00 30
6 7698 BLAKE MANAGER 7839 1981/5/1 2850.00 30
7 7782 CLARK MANAGER 7839 1981/6/9 2450.00 10
8 7788 SCOTT ANALYST 7566 0087/4/19 3000.00 20
9 7839 KING PRESIDENT 1981/11/17 5000.00 10
10 7844 TURNER SALESMAN 7698 1981/9/8 1500.00 0.00 30
11 7876 ADAMS CLERK 7788 0087/5/23 1100.00 20
12 7900 JAMES CLERK 7698 1981/12/3 950.00 30
13 7902 FORD ANALYST 7566 1981/12/3 3000.00 20
14 7934 MILLER CLERK 7782 1982/1/23 1300.00 10
查询dept表记录
SELECT * FROM dept;
deptno dname loc
1 10 ACCOUNTING NEW YORK
2 20 RESEARCH DALLAS
3 30 SALES CHICAGO
4 40 OPERATIONS BOSTON
连接查询语句
SELECT e.ename, d.dname FROM emp e LEFT OUTER JOIN dept d ON(e.deptno = d.deptno); --左外连接
SELECT e.ename, d.dname FROM emp e RIGHT OUTER JOIN dept d ON(e.deptno = d.deptno);--右外连接
SELECT e.ename, d.dname FROM emp e FULL OUTER JOIN dept d ON(e.deptno = d.deptno); --全外连接
三个连接查询结果比较
LEFT OUTER RIGHT OUTER FULL OUTER
1 SMITH RESEARCH 1 CLARK ACCOUNTING 1 SMITH RESEARCH
2 ALLEN SALES 2 KING ACCOUNTING 2 ALLEN SALES
3 WARD SALES 3 MILLER ACCOUNTING 3 WARD SALES
4 JONES RESEARCH 4 JONES RESEARCH 4 JONES RESEARCH
5 MARTIN SALES 5 FORD RESEARCH 5 MARTIN SALES
6 BLAKE SALES 6 ADAMS RESEARCH 6 BLAKE SALES
7 CLARK ACCOUNTING 7 SMITH RESEARCH 7 CLARK ACCOUNTING
8 SCOTT RESEARCH 8 SCOTT RESEARCH 8 SCOTT RESEARCH
9 KING ACCOUNTING 9 WARD SALES 9 KING ACCOUNTING
10 TURNER SALES 10 TURNER SALES 10 TURNER SALES
11 ADAMS RESEARCH 11 ALLEN SALES 11 ADAMS RESEARCH
12 JAMES SALES 12 JAMES SALES 12 JAMES SALES
13 FORD RESEARCH 13 BLAKE SALES 13 FORD RESEARCH
14 MILLER ACCOUNTING 14 MARTIN SALES 14 MILLER ACCOUNTING
15 OPERATIONS 15 OPERATIONS
通过上面表的相关查询结果:
知识准备:
首先应该明白什么是驱动表,说白了就是表所在的位置(表在“LEFT OUTER JOIN”关键字的左边或者右边的位置)。
左外连接:驱动表就是“LEFT OUTER JOIN”关键字的左边的表。
右外连接:驱动表就是“LEFT OUTER JOIN”关键字的右边的表。
全外连接:此时驱动表是“LEFT OUTER JOIN”关键字的两边的表。
sql语句的执行顺序
左外连接:先查询“LEFT OUTER JOIN”关键字左边的表。
右外连接:先查询“LEFT OUTER JOIN”关键字右边的表。
全外连接:先查询“LEFT OUTER JOIN”关键字左边的表(如果查询左边相应的字段为空,那么查询右边表的相应字段,若不为空,则进行匹配)。
区分左外连接、右外连接、全外连接
左外连接:
先查询“LEFT OUTER JOIN”关键字左边表的相应字段,若为空,则不与右边表进行匹配。
右外连接:
先查询“LEFT OUTER JOIN”关键字右边表的相应字段,若为空,则不与左边表进行匹配。
全外连接
先查询“LEFT OUTER JOIN”关键字左边表的相应字段,若为空,查询“LEFT OUTER JOIN”关键字右边表的相应字段,只要一边不为空,则进行匹配。
原文:http://www.cnblogs.com/liuranjsj/p/5002915.html