MySQL视图(view)

2021-06-12  本文已影响0人  一个小运维
视图概述
使用视图的原因

创建视图

语法格式
CREATE [OR REPLACE] [ALGORITHM={UNDEFINED|MERGE|TEMPTABLE}]
VIEW 视图名[(属性清单)]
AS SELECT语句
[WITH [CASCADED|LOCAL] CHECK OPTION];
视图示例
mysql> use test2021;
mysql> create view emp_view
    -> as
    ->   select name, email, dept_name
    ->   from employees as e
    ->   inner join departments as d
    ->   on e.dept_id=d.dept_id;
Query OK, 0 rows affected (0.01 sec)

# 查询视图中数据
mysql> select * from emp_view;
mysql> select * from emp_view where dept_name='运维部';
+-----------+--------------------+-----------+
| name      | email              | dept_name |
+-----------+--------------------+-----------+
| 廖娜      | liaona@guodong.com  | 运维部    |
| 窦红梅    | douhongmei@guodong.com | 运维部    |
| 聂想      | niexiang@guodong.com | 运维部    |
| 陈阳      | chenyang@guodong.com | 运维部    |
| 戴璐      | dailu@guodong.com | 运维部    |
| 陈斌      | chenbin@guodong.com | 运维部    |
+-----------+--------------------+-----------+
6 rows in set (0.00 sec)
mysql> create view emp_sal_view
    -> as
    ->   select name, date, basic+bonus as total
    ->   from employees as e
    ->   inner join salary as s
    ->   on e.employee_id=s.employee_id;
Query OK, 0 rows affected (0.00 sec)

mysql> select * from emp_sal_view where year(date)=2020 and month(date)=12;

修改视图

语法格式
方式一:
CREATE [OR REPLACE] [ALGORITHM={UNDEFINED|MERGE|TEMPTABLE}]
VIEW 视图名[(属性清单)]
AS SELECT语句
[WITH [CASCADED|LOCAL] CHECK OPTION];
mysql> create or replace view emp_view
    -> as
    ->   select name, email, d.dept_id, dept_name
    ->   from employees as e
    ->   inner join departments as d
    ->   on e.dept_id=d.dept_id;
    
mysql> select * from emp_view;
方式二
ALTER VIEW 视图名 AS 查询语句
mysql> alter view emp_sal_view
    -> as
    ->   select name, date, basic, bonus, basic+bonus as total
    ->   from employees as e
    ->   inner join salary as s
    ->   on e.employee_id=s.employee_id;
Query OK, 0 rows affected (0.01 sec)

mysql> select * from emp_sal_view where year(date)=2020 and month(date)=12;

查看视图

SHOW TABLES
DESC 视图

删除视图

DROP VIEW 视图1, 视图2, ...
mysql> drop view emp_view, emp_sal_view;
Query OK, 0 rows affected (0.00 sec)
上一篇 下一篇

猜你喜欢

热点阅读