• mysql-15-view


    #视图
    /*
    含义:虚拟表,和普通表一样使用。通过表动态生成的数据
    
    只保存了sql逻辑,不保存查询结果
    
    应用场景:
    	1、多个地方用到同样的查询结果
    	2、该查询结果使用的sql语句较为复杂
    */
    
    USE students;
    show tables;
    
    #案例:查询姓张的学生名和专业名
    select stu_name, major_name 
    from stuinfo as s
    inner join major m on s.major_id = m.id
    where s.stu_name like '张%';
    
    # 用视图来实现
    # 创建视图
    create view v1 as
    select stu_name, major_name
    from stuinfo as s
    inner join major m on s.major_id = m.id;
    #使用视图
    select * from v1
    where stu_name like '张%';
    
    #一、创建视图
    /*
    语法:
    create view 视图名 as
    查询语句;
    */
    USE myemployees;
    
    #案例1:查询姓名中包含a字符的员工名、部门名和工种信息
    create view myv1 as 
    select last_name,department_name, job_title
    from employees as e
    inner join departments as d on e.department_id = d.department_id
    inner join jobs as j on j.job_id = e.job_id;
    
    select * from myv1
    where last_name like '%a%';
    
    
    #案例2:查询各个部门的平均工资级别
    #1、创建视图查看各个部门的平均工资
    create view myv2 as
    select avg(salary) as ag, department_id
    from employees
    group by department_id;
    #2、使用视图查询对应的级别
    select myv2.ag, g.grade_level
    from myv2
    inner join job_grades as g
    on myv2.ag between g.lowest_sal and g.highest_sal;
    
    #案例3:查询平均工资最低的部门信息
    select * from myv2
    order by ag 
    limit 1;
    
    #案例4:查询平均工资最低的部门名和工资
    create view myv3 as
    select * from myv2 order by ag limit 1;
    
    select e.salary, d.department_name
    from myv3 
    inner join employees as e on myv3.department_id = e.department_id
    inner join departments as d on myv3.department_id = d.department_id;
    
    
    #二、视图的修改
    /*
    方式一
    	create or replace view 视图名 as
    	查询语句;
    
    方式二
    	alter view 视图名 as 
        查询语句;
    */
    
    #三、删除视图
    /*
    drop view 视图名, 视图名, ... ;
    */
    
    
    #四、查看视图
    desc myv3;
    show create view myv3;
    
    #五、视图的更新
    #可以更新,并且会更改原始表。但一般只用于查询
    create or replace view v1 as 
    select last_name, email
    from employees;
    
    select * from v1;
    #1、插入
    insert into v1
    values('张飞', 'zf@qq.com');
    
    #2、修改
    update v1 set last_name='张无忌' where last_name='张飞';
    
    #3、删除
    delete from v1 where last_name='张无忌';
    
    #当视图中含有分组groupby、联结join、子查询、并、聚集函数、distinct、导出(计算列)时,不能更新
    

      

  • 相关阅读:
    高斯过程(GP)
    隐马尔可夫模型(hidden Markov model,HMM)
    php常用配置(php.ini)
    MySQL常用配置
    Discuz论坛搭建过程
    MySQL安装及主从配置
    rsync+inotify实现服务器数据同步
    文件解压缩及打包工具
    vim编辑器的基本操作
    linux笔记_磁盘分区
  • 原文地址:https://www.cnblogs.com/chaojunwang-ml/p/13261677.html
Copyright © 2020-2023  润新知