js css htmlMySQL数据库

MySql视图

2023-02-20  本文已影响0人  技术老男孩

一、MySql视图概念:

二、MySql视图的优点:

三、语法格式:

创建视图

create view 库.视图名称 as Select查询命令;
create view 库.视图名称(字段名列表) as Select查询命令;

查看视图

  • 查看当前库里哪些表是视图
    use 库.视图名称;
    show table status where comment="VIEW"\G
  • 查看视图表里的数据是从哪个基表获取的
    show create view 库.视图名称 \G

操作视图

与普通表一样(select insert update delete)

删除视图

drop view 库.视图名称;

四、使用示例:

# 创建一个库,用来存放视图表
mysql> create database viewdb1;
# 创建一个基于tarena.user表的视图
mysql> create view viewdb1.vtab1(姓名,用户编号) as select name,uid from tarena.user;
Query OK, 0 rows affected (0.00 sec)
mysql> desc viewdb1.vtab1;
+--------------+----------+------+-----+---------+-------+
| Field        | Type     | Null | Key | Default | Extra |
+--------------+----------+------+-----+---------+-------+
| 姓名         | char(20) | YES  |     | NULL    |       |
| 用户编号     | int(11)  | YES  |     | NULL    |       |
+--------------+----------+------+-----+---------+-------+
2 rows in set (0.00 sec)
# 进入viewdb1视图表中
mysql> use viewdb1
# 查看当前库里哪些表是视图
mysql> show table status where comment="VIEW" \G
*************************** 1. row ***************************
           Name: vtab
         Engine: NULL
        Version: NULL
     Row_format: NULL
           Rows: NULL
 Avg_row_length: NULL
    Data_length: NULL
Max_data_length: NULL
   Index_length: NULL
      Data_free: NULL
 Auto_increment: NULL
    Create_time: NULL
    Update_time: NULL
     Check_time: NULL
      Collation: NULL
       Checksum: NULL
 Create_options: NULL
        Comment: VIEW
# 查看视图表里的数据是从哪个基表获取的
mysql> show create view viewdb1.vtab1 \G
*************************** 1. row ***************************
                View: vtab1
         Create View: CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `vtab1` AS select `tarena`.`user`.`name` AS `姓名`,`tarena`.`user`.`uid` AS `用户编号` from `tarena`.`user`
character_set_client: utf8
collation_connection: utf8_general_ci
1 row in set (0.00 sec)
mysql> drop viewdb1.vtab;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'viewdb1.vtab' at line 1
# 需要加上view才能删除成功
mysql> drop view viewdb1.vtab;
Query OK, 0 rows affected (0.00 sec)
上一篇下一篇

猜你喜欢

热点阅读