• CREATE VIEW 语句中嵌入子查询
  1. CREATE [OR REPLACE]
  2. [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
  3. VIEW 视图名称 [(字段列表)]
  4. AS 查询语句
  5. [WITH [CASCADED|LOCAL] CHECK OPTION]
  • 精简版
  1. CREATE VIEW 视图名称
  2. AS 查询语句

3.1 创建单表视图

举例:

  1. CREATE VIEW empvu80
  2. AS
  3. SELECT employee_id, last_name, salary
  4. FROM employees
  5. WHERE department_id = 80;

查询视图:

  1. SELECT *
  2. FROM salvu80;

1555430882363.png举例:

  1. CREATE VIEW emp_year_salary (ename,year_salary)
  2. AS
  3. SELECT ename,salary*12*(1+IFNULL(commission_pct,0))
  4. FROM t_employee;

举例:

  1. CREATE VIEW salvu50
  2. AS
  3. SELECT employee_id ID_NUMBER, last_name NAME,salary*12 ANN_SALARY
  4. FROM employees
  5. WHERE department_id = 50;

说明1:实际上就是我们在 SQL 查询语句的基础上封装了视图 VIEW,这样就会基于 SQL 语句的结果集形成一张虚拟表。

说明2:在创建视图时,没有在视图名后面指定字段列表,则视图中字段列表默认和SELECT语句中的字段列表一致。如果SELECT语句中给字段取了别名,那么视图中的字段名和别名相同。

3.2 创建多表联合视图

举例:

  1. CREATE VIEW empview
  2. AS
  3. SELECT employee_id emp_id,last_name NAME,department_name
  4. FROM employees e,departments d
  5. WHERE e.department_id = d.department_id;
  1. CREATE VIEW emp_dept
  2. AS
  3. SELECT ename,dname
  4. FROM t_employee LEFT JOIN t_department
  5. ON t_employee.did = t_department.did;
  1. CREATE VIEW dept_sum_vu
  2. (name, minsal, maxsal, avgsal)
  3. AS
  4. SELECT d.department_name, MIN(e.salary), MAX(e.salary),AVG(e.salary)
  5. FROM employees e, departments d
  6. WHERE e.department_id = d.department_id
  7. GROUP BY d.department_name;
  • 利用视图对数据进行格式化

我们经常需要输出某个格式的内容,比如我们想输出员工姓名和对应的部门名,对应格式为 emp_name(department_name),就可以使用视图来完成数据格式化的操作:

  1. CREATE VIEW emp_depart
  2. AS
  3. SELECT CONCAT(last_name,'(',department_name,')') AS emp_dept
  4. FROM employees e JOIN departments d
  5. WHERE e.department_id = d.department_id

3.3 基于视图创建视图

当我们创建好一张视图之后,还可以在它的基础上继续创建视图。

举例:联合“emp_dept”视图和“emp_year_salary”视图查询员工姓名、部门名称、年薪信息创建 “emp_dept_ysalary”视图。

  1. CREATE VIEW emp_dept_ysalary
  2. AS
  3. SELECT emp_dept.ename,dname,year_salary
  4. FROM emp_dept INNER JOIN emp_year_salary
  5. ON emp_dept.ename = emp_year_salary.ename;