1. 程式人生 > 其它 >Oracle資料庫(三)表操作,連線查詢,分頁

Oracle資料庫(三)表操作,連線查詢,分頁

複製表

--複製表
create table new_table as select * from Product
--複製表結構不要資料
create table new_table as select * from Product where 1=2

在where後面跟一個不成立的條件,就會僅複製表的結構而不復製表的內容。

刪除表

--刪除表
delete table new_table
--刪除表,無法找回
truncate table new_table

序列

序列(SEQUENCE)其實是序列號生成器,可以為表中的行自動生成序列號,產生一組等間隔的數值(型別為數字)。其主要的用途是生成表的主鍵值,可以在插入語句中引用,也可以

通過查詢檢查當前值,或使序列增至下一個值。

 使用語句建立序列

----建立序列
create sequence user_seq
increment by 1 
start with 1
nomaxvalue
nominvalue
nocache

多表查詢

select * from p_emp e ,p_dept d where e.deptno=d.deptno

笛卡爾積

 笛卡爾積在sql中實現的方式是交叉連線,所有連線方式都會先生成臨時笛卡爾積表,笛卡爾積是關係代數的一個概念,表示兩個表中每一行資料任意組合。

簡單來說,就是兩個表不加條件限制的進行連線,出現的資料行數是兩個表資料行數的乘積。

內連線

select * from p_emp e ,p_dept d where e.deptno=d.deptno

內連線的侷限性:如果有空值,查詢結果可能會有缺失。

解決辦法:

以一個表為基準進行外連結:

--左外連結
select * from p_emp e left join p_dept d on e.deptno=d.deptno

或者使用 +  符號

select * from p_emp e, p_dept d where e.deptno=d.deptno(+)

 查詢使用者的表

--查詢所有表
select * from user_tables

自連線

有些情況可能會遇到,將一個表的相同或者不同列的資料進行比較,需要將一個表來進行當做兩個表進行自連線,進而比較其中的資料再進行查詢

--自連線
select e1.ename,e2.ename from p_emp e1,p_emp e2 where e1.empno=e2.mgr

層次查詢

oracle中的select語句可以用START WITH...CONNECT BY PRIOR子句實現遞迴查詢,connect by 是結構化查詢中用到的,其基本語法是:

select ... from <TableName>
where <Conditional-1>
start with <Conditional-2>
connect by <Conditional-3>
;

<Conditional-1>:過濾條件,用於對返回的所有記錄進行過濾。
<Conditional-2>:查詢結果重起始根結點的限定條件。
<Conditional-3>:連線條件
--層次查詢
select e.*,level from p_emp e connect by prior e.empno=e.mgr start with e.ename='KING' order by level

偽列: level rownum

rownum是oracle系統順序分配為從查詢返回的行的編號,返回的第一行分配的是1,第二行是2,依此類推,這個偽欄位可以用於限制查詢返回的總行數,

而且rownum不能以任何表的名稱作為字首。

需要注意的是:如果按照主鍵排序,rownum的順序會跟著變化,如果不是按照主鍵排序,rownum不會變。

--查詢前十列資料
select e.*,rownum from p_emp e where rownum <=10
--6-10列資料,巢狀查詢
select * from (select e.*,rownum rownu from p_emp e where rownum <=10) r where r.rownu >5