当前位置: 移动技术网 > IT编程>开发语言>.net > oracle-sql左右连接/ 临时表创建

oracle-sql左右连接/ 临时表创建

2020年07月07日  | 移动技术网IT编程  | 我要评论
  1. 左右连接
    左外连接(左边的表不加限制)
    右外连接(右边的表不加限制)
    全外连接(左右两表都不加限制

对应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);

  1. 临时表
    在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 临时表名;

本文地址:https://blog.csdn.net/qq_39503451/article/details/107163794

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网