/*薪资等级表*/ DROP TABLE IF EXISTS `job_grades`; CREATE TABLE `job_grades`( `grade_level` varchar(3) comment '等级', `lowest_sal` int comment '薪资最低值', `highest_sal` int comment '薪资最高值', PRIMARY KEY (`grade_level`) ) comment '薪资等级表';
第二步,插入数据,数据在Gitee上,因此这里就忽略,且这里的数据就是前面在学习子查询时的数据。
创建视图
创建视图的语法格式如下所示:
1
create view 视图名 as 查询语句;
也就是说使用视图分为两个步骤,第一步是创建视图;第二步是对视图执行查询操作。
例子1:查询姓名中包含a字符的员工名称、部门和工作名称。
第一步,创建视图myview1:
1 2 3 4 5
create view myview1 as select e.last_name,d.department_name,j.job_title from employees as e,jobs as j,departments as d where e.employee_id = d.department_id and e.job_id = j.job_id;
第二步,使用视图,如下所示:
1
select * from myview1 as m1 where m1.last_name like '%a%';
运行结果如下所示:
当然开发者也可以直接创建视图,此时SQL如下所示:
1 2 3 4 5 6
create view myview1 as select e.last_name,d.department_name,j.job_title from employees as e,jobs as j,departments as d where e.last_name like '%a%' and e.employee_id = d.department_id and e.job_id = j.job_id;
create view myview2 as select e.department_id as 部门id,e.asvg as 平均工资,jg.grade_level as 工资级别 from ( select department_id, avg(salary)as asvg from employees group by department_id ) as e,job_grades as jg where e.asvg between jg.lowest_sal and jg.highest_sal;
第二步,使用视图,如下所示:
1
select * from myview2;
运行结果如下所示:
修改视图
可以使用两种方法来对视图进行修改:如果视图存在则修改,不存在则创建;直接修改视图。
方法1:如果该视图存在,则修改;不存在则创建新的视图,此时使用的SQL语法格式如下所示:
1
create or replace view 视图名 as 查询语句;
例子3:查询每个job_id的平均薪水,显示job_id和平均薪水:
1 2 3 4
create or replace view myview3 as select job_id,avg(salary) as avsg from employees group by job_id;
--查询数据 mysql> select * from myview4 where email like '%envy%'; +-----------+------------------+ | last_name | email | +-----------+------------------+ | book | envythink@qq.com | +-----------+------------------+ 1 row in set (0.00 sec)
--删除数据 mysql> delete from myview4 where last_name = 'book'; Query OK, 1 row affected (0.68 sec) --查询数据 mysql> select * from myview4 where email like '%envy%'; Empty set (0.00 sec)