1007.Oracle中的基础对象
表、视图、索引、同义词、序列
index --提升sql语句的查询性能
view --封装查询sql/数据权限控制
synonym --区别名(可以用来隐藏模式名)
sequence --主键用的
查看数据库对象
select * from dba_objects;
select * from user_objects;
1、索引
create index index_name on table_name(column_name);
alter indes pk_deptno REBUILD STORAGE(INITIAL 1M NEXT 512K);
drop index index_name;
eg.
drop table test;
create table test as select * from dba_objects;
select count(*) from test where object_id=1000;
用全表扫描好,还是用索引好?
取决要查找的数据量。要查找的数据越少,用索引也好;要查找的数据占全部的一半用全表扫描好。
set autot trace;
SQLPLUS中打开AUTOTRACE开关可以得到SQL的执行计划。
创建索引:
create index idx_id on test(object_id);
索引名 什么上创建 哪一列上
select * from test where object_id=1000;
select owner, count(*) from test group by order 2 desc;
create index idx_owner on test(owner);
组合索引(不止一个列)
create index idx_owner on test(object_id,owner);
select * from user_objects;
查看当前用户的索引信息
select * from user_indexes;(查看索引建在哪一个对象/表上面)
查看索引建在哪一个列上面
select index_name, colum_position, descend, column_name
from dba_ind_columns
where table_owner='SCOTT' and table_name = 'TEST'
order by 1,2;
索引针对表的列创建的,不一定能提升查询性能
2、视图 view
create [or replace] view_name as select ...
drop view view_name
eg.
create or replace view emp1 as select * from emp where sal>2000;
select * from user_objects;
select * from emp1;等价于select * from emp where sal>2000;
视图的作用:
二次使用时可简化代码;
控制权限(如查看数据范围的权限);
select * from emp;
视图与权限结合使用
create or replace view emp_new as select * from emp where sal < 2000;
grant select on emp_new to test;
SELECT * FROM DBA_OBJECTS WHERE OBJECT_NAME='EMP1';
查看视图源码定义:(右键‘view’)
SELECT * FROM DBA_VIEWS WHERE VIEW_NAME='EMP1';
3、同义词 synonym
create sequence [user.]sequence_name [increment by n] [start with n] [maxvalue n | nomaxvalue] [minvalue n | nominvalue];
drop sequence sequence_name;
eg.
create or replace synonym snm for emp;
select * from snm ;
查看同义词:
select * from dba_synonyms where synonym_name = 'SNM';
删除同义词:
drop synonym snm ;
4、序列 sequence (递增的)
create [or replace] [public] synonym synonym_name for object_name;
drop synonym synonym_name
eg.
create sequence seq_sz_stu
start with 1 --初始值
increment by 1 --增长的步长
minvalue 1 --最小值
maxvalue 9999999999999 --最大值
order --按有序取值,noorder是无序取值
cache 5000 --每次预分配多少个
nocycle --如果到了最大值,是否从头开始
select seq_sz_stu.nextval from dual; --取下一个值
select seq_sz_stu.currval from dual; --取当前的值
select * from user_objects;
select seq_id.nextval from dual; ---启用
dual是个虚表,select后面是什么,dual里面就放什么。
select seq_id.nextval from dual;
select seq_id.currval from dual;
select * from dba_sequences where sequence_name = 'SEQ_ID';
序列的值正常情况下是不会重复的
序列是给主键用的。
create table t(id number primary key);
insert into t values(seq_id,nextval);
select * from t;
序列 会跳号(进行rollback操作后) 跳号没法解决。