介绍
视图(View)是一种虚拟存在的表。视图中的数据并不在数据库中实际存在,行和列数据来自查询中使用的表,并且是在使用视图时动态生成的。视图只保存了查询的SQL逻辑,不保存查询结果
语法
1). 创建
CREATE [OR REPLACE] VIEW 视图名称[(列名列表)] AS SELECT语句 [ WITH [
CASCADED | LOCAL ] CHECK OPTION ]
例如:
CREATE OR REPLACE VIEW stu_v_1 AS SELECT id,NAME FROM student WHERE id <= 10;
2). 查询
查看创建视图语句:SHOW CREATE VIEW 视图名称;
查看视图数据:SELECT * FROM 视图名称 ...... ;
例如:
SHOW CREATE VIEW stu_v_1;
SELECT * FROM stu_v_1;
SELECT * FROM stu_v_1 WHERE id < 3;
3). 修改
方式一:CREATE [OR REPLACE] VIEW 视图名称[(列名列表)] AS SELECT语句 [ WITH
[ CASCADED | LOCAL ] CHECK OPTION ]
例如:
CREATE OR REPLACE VIEW stu_v_1 AS SELECT id,NAME,NO FROM student WHERE id <= 10;
方式二:ALTER VIEW 视图名称[(列名列表)] AS SELECT语句 [ WITH [ CASCADED |
LOCAL ] CHECK OPTION ]
例如:
ALTER VIEW stu_v_1 AS SELECT id,NAME FROM student WHERE id <= 10;
4). 删除
DROP VIEW [IF EXISTS] 视图名称 [,视图名称] ...
例如:
DROP VIEW IF EXISTS stu_v_1;