1.
/*
含义:虚拟表,和普通表一样使用
mysql5.1版本出现的新特性,是通过表动态生成的数据
创建语法的关键字 是否实际占用物理空间 使用
视图 create view 只是保存了sql逻辑 增删改查,只是一般不能增删改
表 create table 保存了数据 增删改查
*/
1.1 案例:查询姓张的学生名和专业名
SELECT stuname,majorname
FROM stuinfo s
INNER JOIN major m ON s.`majorid`= m.`id`
WHERE s.`stuname` LIKE '张%';
CREATE VIEW v1
AS
SELECT stuname,majorname
FROM stuinfo s
INNER JOIN major m ON s.`majorid`= m.`id`;
SELECT * FROM v1 WHERE stuname LIKE '张%';
2. 创建视图 (类似于封装)
语法:
create view 视图名
as
查询语句;
2.1. 查询姓名中包含a字符的员工名、部门名和工种信息
#1.创建
create view myv1
AS
select last_name,department_name,job_title
FROM employees e
JOIN departments d ON e.department_id = d.department_id
JOIN jobs j ON j.job_id= e.job_id;
#2.使用
SELECT * FROM myv1 WHERE LAST_NAME LIKE '%a%';
2.2 查询各部门的平均工资级别
#1.创建视图查看各个部门平均工资
CREATE VIEW myv2
AS
SELECT AVG(salary) ag,department_id
FROM employees
GROUP BY department_id;
#2.使用
SELECT myv2.ag,g.grade_level
FROM myv2
JOIN JOB_GRADES g
ON myv2.ag BETWEEN g.lowest_sal AND g.highest_sal;
2.3 查询平均工资最低的部门信息
SELECT * FROM myv2 ORDER BY ag LIMIT 1;
2.4 查询平均工资最低的部门名和工资
CREATE VIEW myv3
AS
SELECT * FROM myv2 ORDER BY ag LIMIT 1;
SELECT d.*,m.ag
FROM myv3 m
JOIN departments d
ON d.department_id=m.department_id;
3.视图的修改
3.1 方式一:
create or replace view 视图名
as
查询语句;
SELECT * FROM myv3
CREATE OR REPLACE VIEW myv3
AS
SELECT AVG(salary),job_id
FROM employees
GROUP BY job_id;
3.2 方式二:
alter view 视图名
as
查询语句;
ALTER VIEW myv3
AS
SELECT * FROM employees;
4.删除视图
语法:drop view 视图名,视图名,…;
DROP VIEW myv1,myv2,myv3;
5. 查看视图
DESC myv3;
SHOW CREATE VIEW myv3;
6.练习
6.1 创建视图emp_v1,要求查询电话号码以’011’开头的员工姓名,工资和邮箱
CREATE OR REPLACE VIEW emp_v1
AS
SELECT last_name,salary,email
FROM employees
WHERE phone_number LIKE '011%';
6.2 创建视图emp_v2,要求查询部门的最高工资高于12000的部门信息
CREATE OR REPLACE VIEW emp_v2
AS
SELECT MAX(salary),department_id
FROM employees
GROUP BY department_id
HAVING MAX(salary)>12000;
func BindForm(form interface{}, c *gin.Context) error {
MForm, err := c.MultipartForm()
if err != nil {
zlog.SugarLogger.Errorf(err.Error())
response.FailByFormError(c)
return err
}
err = response.Decoder.Decode(form, MForm.Value)
if err != nil {
zlog.SugarLogger.Errorf(err.Error())
response.FailByFormError(c)
return err
}
return err
}