- 左右连接
左外连接(左边的表不加限制)
右外连接(右边的表不加限制)
全外连接(左右两表都不加限制
对应sql:left/right/full outer join。 通常省略outer关键字, 写成:left/right/full join。
在左连接和右连接时都会以一张a表为基础表,该表的内容会全部显示,然后加上a表和b表匹配的内容。 如果a表的数据在b表中没有记录。 那么在相关联的结果集行中列显示为空值(null)。
左外连接(left outer join/ left join)
left join是以左表的记录为基础的,示例中t_a可以看成左表,t_b可以看成右表,它的结果集是t_a表中的全部数据,再加上t_a表和t_b表匹配后的数据。换句话说,左表(t_a)的记录将会全部表示出来,而右表(t_b)只会显示符合搜索条件的记录。t_b表记录不足的地方均为null。
select * from t_a a left join t_b b on a.id = b.id;
或
select * from t_a a left outer join t_b b on a.id = b.id;
用( )来实现, 这个 号可以这样来理解: 表示补充,即哪个表有加号,这个表就是匹配表。如果加号写在右表,左表就是全部显示,所以是左连接。
select * from t_a a,t_b b where a.id=b.id( );
右外连接(right outer join/right join)
和left join的结果刚好相反,是以右表(t_b)为基础的。它的结果集是t_b表所有记录,再加上t_a和t_b匹配后的数据。 t_a表记录不足的地方均为null。
select * from t_a a right join t_b b on a.id = b.id;
或
select * from t_a a right outer join t_b b on a.id = b.id;
用( )来实现, 这个 号可以这样来理解: 表示补充,即哪个表有加号,这个表就是匹配表。如果加号写在左表,右表就是全部显示,所以是右连接。
select * from t_a a,t_b b where a.id( )=b.id;
全外连接(full outer join/full join)
左表和右表都不做限制,所有的记录都显示,两表不足的地方均为null。 全外连接不支持( )写法。
select * from t_a a full join t_b b on a.id = b.id;
或
select * from t_a a full outer join t_b b on a.id = b.id;
select * from t_a a,t_b b where a.id = b.id;
select * from t_a a join t_b b on a.id = b.id;
select * from t_a a where a.id in (select b.id from t_b b);
select * from t_a a where exists (select 1 from t_b b where a.id = b.id);
- 临时表
在oracle中,临时表分为会话级别(session)和事务级别(transaction)两种。
会话级的临时表在整个会话期间都存在,直到会话结束;事务级别的临时表数据在transaction结束后消失,即commit/rollback或结束会话时,会清除临时表数据。
1、事务级临时表 on commit delete rows; 当commit的时候删除数据(默认情况)
2、会话级临时表 on commit preserve rows; 当commit的时候保留数据,当会话结束删除数据
1.会话级别临时表
会话级临时表是指临时表中的数据只在会话生命周期之中存在,当用户退出会话结束的时候,oracle自动清除临时表中数据。
创建方式1:
create global temporary table temp1(id number) on commit preserve rows;
insert into temp1values(100);
select * from temp1;
创建方式2:
create global temporary table temp1 on commit preserve rows as select id from 另一个表;
select * from temp1;
这个时候,在当前会话查询数据就可以查询到了,但是再新开一个会话窗口查询,就会发现temp1是空表。
2.事务级别的临时表
创建方式1:
create global temporary table temp2(id number) on commit delete rows;
insert into temp2 values(200);
select * from temp2;
创建方式2:
create global temporary table temp2 as select id from 另一个表;(默认创建的就是事务级别的)
select * from temp2;
这时当你执行了commit和rollback操作的话,再次查询表内的数据就查不到了。
3.oracle的临时表创建完就是真实存在的,无需每次都创建。
若要删除临时表可以:
truncate table 临时表名;
drop table 临时表名;