代码改变世界

左外连接,右外连接,全外连接

2019-05-26 10:37  Gizing  阅读(6363)  评论(0编辑  收藏  举报

左外连接

  • 用在查询块的from短语中
  • 又称左连接,列出左边所有元组,A left join B on 条件表达式 中的on决定了B表中符合条件表达式的数据才保留,不符合的记录,B表字段为null
  • where短语的条件等到外连接结束后才使用,对外连接结果进行过滤(这个与SQL语句中各算子的执行顺序有关)

例子:
create table t1(c1 int primary key, c2 int);
create table t2(cc1 int primary key, cc2 int);
insert into t1 values (1,1),(2,2),(5,5);
insert into t2 values (2,2),(3,3),(4,4);
select * from t1 left join t2 on t1.c2=t2.cc2;
结果:

c1 c2 cc1 cc2
2 2 2 2
1 1 null null
5 5 null null

右外连接

同左外连接,只不过是列出右边所有元组,又称右连接

全外连接

左右表的所有元组均列出(且各只出现一次),不符合on表达式的字段为null