Oracle从小白到精通第六天( oracle中的视图view)(尚硅谷学习Oracle笔记)
1.视图的基本含义
从表中抽出的逻辑上相关的数据集合。在修改视图的时候,原表的信息也跟着修改。
在有下面两种情况下使用视图,针对不同的用户提供不同的权限,根据权限提供不同的访问信息,修改的时候要全部修改。
2.创建视图
1. 创建一个简单的视图
create view empview
as
select employee_id,last_name,salary
from employees
where department_id=80
2. 修改视图中的数据
update empview
set salary=20000
where employee_id =179;
在你更改了视图中的数据的时候,基于原表中的数据也做了修改
其中的增删改查与表的操作一样
3. 创建一个基于多个表的视图 这样可以简化查询
create view empview2
as
select employee_id id ,last_name name ,salary,department_name
from employees e,departments d
where e.department_id=d.department_id
3.修改视图
create or replace view empview2
as
select employee_id id ,last_name name ,department_name
from employees e,departments d
where e.department_id=d.department_id
当你不希望用户对视图进行增删改的时候只需要在最后添加一个 with read only
create or replace view empview2
as
select employee_id id ,last_name name ,department_name
from employees e,departments d
where e.department_id=d.department_id
with read only
4. 复杂视图
复杂视图创建的时候对不存在的列必须使用一个别名
在复杂视图中一般不能使用增删改的操作DML
create or replace view empview3
as
select department_name, avg(salary) a_salary
from employees e , departments d
where e.department_id = d.department_id
group by department_name
5.删除视图
drop view empview3;
6. Top—N 分析
Top-N分析是指查询一个列中最大或最小的n个值
查询employees表中工资前十的人
思想是先把排序好的薪水作为一个表,然后就有一个伪列,在根据伪列进行排序。
rownum是一个伪列
select rownum,employee_id, last_name,salary
from(
select employee_id,last_name,salary
from employees
order by salary desc
)
where rownum<=10
查询employees表中工资40-50的人
因为不能使用> 所以只能再查询一次把rownum变成一个真实的列
select rn,employee_id, last_name,salary
from(
select rownum rn,employee_id, last_name,salary
from(
select employee_id,last_name,salary
from employees
order by salary desc
)
)
where rn>40 and rn <=50
一个数据库的分页查询
对 oralce 数据库中记录进行分页: 每页显示 10 条记录, 查询第 5 页的数据
select employee_id, last_name, salary
from (
select rownum rn, employee_id, last_name, salary
from employees
) e
where e.rn <= 50 and e.rn > 40
注意: **对 oracle 分页必须使用 rownum “伪列”!
这是一个通用的格式
select employee_id, last_name, salary
from (
select rownum rn, employee_id, last_name, salary
from employees
) e
where e.rn <= pageNo * pageSize and e.rn > (pageNo - 1) * pageSize