连接分为内连接和外连接(3种),下面举个例子:
(借鉴:http://www.blogjava.net/hello-yun/archive/2011/04/08/347890.html)
表TESTA,TESTB,TESTC,各有A, B两列:
| A | B |
| 001 | 10A |
| 002 | 20A |
| A | B |
| 001 | 10B |
| 003 | 30B |
| A | B |
| 001 | 10C |
| 004 | 40C |
1.内连接:
select * from testA inner join testB on testA.A = testB.A;
select * from testA join testB on testA.A = testB.A;
相当于:
select * from testA,testB where testA.A = testB.A;
即:表A和表B的交集(A∩B)
结果为:
| A | B |
| 001 | 10A |
| 001 | 10B |
2.左外连接:
select * from testA left outer join testB on testA.A = testB.A;
select * from testA left join testB on testA.A = testB.A;
相当于:
select * from testA,testB where testA.A = testB.A(+);
即:左边的表A加上A和B的交集(A∪(A∩B))
结果为:
| A | B |
| 001 | 10A |
| 002 | 20A |
| 001 | 10B |
3个表做左外连接:
select * from testA left join testB on testA.A = testB.A left join testC on testA.A = testC.A;
即:A∪(A∩B)∪(A∩C)
结果为:
| A | B |
| 001 | 10A |
| 002 | 20A |
| 001 | 10B |
| 001 | 10C |
3.右外连接
select * from testA right join testB on testA.A = testB.A;
即:B∪(A∩B)
结果为:
| A | B |
| 001 | 10A |
| 001 | 10B |
| 003 | 30B |
4.全外连接
select * from testA full join testB on testA.A = testB.A;
即:A∪B
注意:全连接不支持(+)写法!
结果为:
| A | B |
| 001 | 10A |
| 002 | 20A |
| 001 | 10B |
| 003 | 30B |
更深入研究请参考:http://www.cnblogs.com/wishyouhappy/p/3678852.html
浙公网安备 33010602011771号