天天看點

Oracle基本操作六:子查詢,rownum,rowid

--子查詢:子查詢(内部查詢)在主查詢前執行一次,結果被用于主查詢(外部查詢)

--子查詢-例:查出比Allen工資高的人

select ename from emp where sal>(select sal from emp where ename='allen')

--子查詢-單行子查詢:隻傳回一行結果,關鍵詞:> = <等。若傳回多個結果,則報錯。

--子查詢-使用組函數:查工資比平均工資高

select ename from emp where sal>(select avg(sal) from emp)

--子查詢-多行子查詢:返加多個結果,需用:

  in  :符合所有結果,

  any :與每個結果比較。如小于最大的,或大于最小的

  all :與每個結果比較。如小于最小的,或大于最大的

--exists:判斷子查詢是true或false,若ture,則執行主查詢

select * from b where where exists(select * from b where b.aid=1);

--exists解析:是采用loop的方式,循環地次數對exists影響很大。

   --若外表資料量小(a)而内表(b)資料量非常大,查詢會很快

--exists和in:若用in,則相反。内表(b)資料量小而外表(a)資料量大,則查詢會很快

--rownum:僞列,資料表中不存在,隻在結果集中存在,用于标記結果集的順序遞加)

   --隻有存在rownum=1的資料,才可能存在rownum=2的資料

select rownum,deptno,deptname from dept;

--rownum用途:分頁

select empno,enme from (select  rownum tempid,empno,ename from emp t) t where t.tempid between 5 and  ;

--rowid:僞數列,對應于每一行資料,固定且唯一,存入資料時已經确定,是18位的二進制的字元

   --可以用rowid來進行查詢,速度快,

   --隻有表發生移動(表空間變化,導入,導出)rowid才會發生變化

select rowid,empno,ename,from emp where rowid='AAAR3qAAEAAAACHAAA';

--rowid用途一:查詢資料,

--rowid用途二:删除重複資料:1.完全删除,2,删除重複的資料,但保留一條

   --方法一:建臨時表,distinct,再删原表,臨時表資料再插入原表,效率高

   --方法二:效率低

delete from  tb_test where rowid in(select a.rowid as id) from  tb_test a,tb_test b

where a.rowid>b.rowid and a.name=b.name and a.age=b.age;

   --方法三:not in 效率最低 因為 not 不帶索引

delete from tb_test a where rowid not in (select  max(b.rowid) from tb_test b where

a.name=b.name and a.age=b.age;