视图

视图是一种虚拟的表。视图中的数据在数据库中并不实际存在。视图中的数据来自定义视图的查询的数据库表,并且是在使用时动态生成的。

通俗的讲,视图只保存查询数据的sql逻辑,并不保存执行结果

视图的创建

1
create [or replace] view 视图名称[(列名列表)] as select语句

例如:

1
2
3
create or replace view user_view as select id, username from user where id < 5;
# 执行查询语句测试
select * from user_view

image-20250410224836654

视图的查询

类似数据库表

视图的修改

必须携带【or replace】参数

1
create or replace view user_view as select id, username from user where id < 10

删除视图

1
drop view [if exists] 视图名称;

对视图添加修改数据

添加数据

  1. 新建一张用户表,添加一些测试数据,如下图:

    image-20250427112927204

  2. 创建视图

    1
    create or replace view user_vw as select id, username, password from `user`
  3. 此时打开视图,可以看到视图创建成功了。

    image-20250427113318969

  4. 此时我们编写一条sql,往视图中插入一条数据

    1
    insert into user_vw values('123','user_10023', 'passwd_123456')
  5. 可以发现执行插入语句并没有报错,我们可以在数据库表user中查看这条插入的数据

    image-20250427113426762

  6. 同样可以在视图user_vw中看到这条数据

    image-20250427113905061

乍一看好像没什么问题哈,此时我们修改一下创建视图的语句

1
create or replace view user_vw as select id, username, password, age from `user` where age < 20

此时视图变成如下的形状

image-20250427114413695

再执行一条插入语句:

1
insert into user_vw values ('222', 'test', 'test', 22)

sql执行成功,此时我们查看数据库表中和视图中的数据,此时我们可以发现,数据库表中存在数据,但是视图中不存在!!!

数据库表

image-20250427115200472

视图

image-20250427115145602

出现的原因就是视图筛选了年龄为20岁以下的用户

此时我通过视图插入的数据,但是在视图中却看不到,是不是不太合理?

所以我们可以给他添加一个检查选项

检查选项

我们可以在创建视图的语句后添加一段语句:

1
with cascaded check option

修改原来创建视图的语句:

1
create or replace view user_vw as select id, username, password from user where age < 20 with cascaded check option;

再次执行插入数据的语句:

1
insert into user_vw values ('1', 'test', 'test', 16);
1
insert into user_vw values ('2', 'test2', 'test2', 28);

可以看到第一条数据正常插入,第二条数据因为与创建视图的条件相违背,所以在插入的时候报错了。

image-20250427120112088