僞列
Oracle 中僞列就像一個表列(表中的列),但是它并沒有存儲在表中,僞列可以從表中查詢,但不能插入、更新和删除它們的值,在Oracle中我們常見的僞列有兩個分别為rownum 和 rowid,它實在我們的表生成之後才添加的,也就是說當select映射之後,才會生成,那麼當 有語句的執行順序在select之後時rownum的順序會随着排序改變順序
Oracle中如果要查詢某張表中多個字段,又隻對某個字段去重的時候用distinct或者group by都不行。distinct和group by會對要查詢的字段一起進行去重,也就是當查詢的所有字段都相同,oracle才認為是重複的。這時用rowid是個不錯的選擇。如下,有一張mytest表,中有id,naem,age字段,如果隻想對name和age 字段進行去重并且保留id字段就可以使用下面的代碼
create table mytest(
id int primary key not null,
name varchar(10) not null,
age int not null
);
insert into mytest values ('1','zs','40');
insert into mytest values ('2','zs','40');
insert into mytest values ('3','ls','30');
insert into mytest values ('4','ww','25');
insert into mytest values ('5','ls','30');
commit;
-- 使用rowid去重的代碼 即内外表關聯
select id,name,age from mytest t1
where t1.rowid in (
select max(t2.rowid) from mytest t2 where t1.name= t2.name and t1.age=t2.age);
t1和t2中rowid是一個字段,因為t1和t2是一張表
原理實際上是test表以name和age字段進行自查詢,對于name和age中沒有重複的資料rowid隻有一個值,是以max/mian(rowid)就是rowid本身,但是對于name和age中重複的資料rowid會有多個,取max/min的一個,這樣就去重了,由于rowid (僞列,資料的實體位址資訊)是以此方法是是通過檔案去操作資料,效率是最高的。