左外连接和右外连接
表A 表B
1 zhangsan 2 zhangsan
2 zhangsan 3 zhangsan
3 wangwu 4 5345345
4 zhangsan 5 zhangsan
如果是左外连接的话,sql语句(Oracle除外)为
select * from A a left outer join B b on a.id=b.id
where a.name="zhangsan";
结果为
+----+----------+------+----------+
| id | name | id | name |
+----+----------+------+----------+
| 1 | zhangsan | NULL | NULL |
| 2 | zhangsan | 2 | zhangsan |
| 4 | zhangsan | 4 | 5345345 |
+----+----------+------+----------+
可以看出,左外连接先根据a.name="zhangsan"将表A的记录查出来,然后根据a.id=b.id,将表B的记录查出来,查询B的过程中如果a.id在B中找不到与之相等的b.id,就补空,查到了即显示结果
右外连接是一样的,读者可以模仿左外连接得出结论
select * from A a right outer join B b on a.id=b.id
where b.name="zhangsan";
+------+----------+----+----------+
| id | name | id | name |
+------+----------+----+----------+
| 2 | zhangsan | 2 | zhangsan |
| 3 | wangwu | 3 | zhangsan |
| NULL | NULL | 5 | zhangsan |
+------+----------+----+----------+